Skip to content

Instantly share code, notes, and snippets.

@Denver-sn
Created September 17, 2021 15:49
Show Gist options
  • Select an option

  • Save Denver-sn/c1b79b3912048bbe12a3a5effd046a23 to your computer and use it in GitHub Desktop.

Select an option

Save Denver-sn/c1b79b3912048bbe12a3a5effd046a23 to your computer and use it in GitHub Desktop.
Example pyTelegramBotAPI with SQLite3 #1
import sqlite3
import telebot
TOKEN = "<YOUR BOT TOKEN>"
bot = telebot.TeleBot(TOKEN)
# I suggest you to download SQLite Studio for creating database and tables...
conn = sqlite3.connect('database.db', check_same_thread=False) # Connecting to the database
cursor = conn.cursor()
# For add someone in the database
def db_table_val(user_id: int, user_name: str):
cursor.execute('INSERT INTO user_data (user_id, user_name) VALUES (?, ?)',
(user_id, user_name))
conn.commit()
@bot.message_handler(commands=['start'])
def send_welcome(message):
us_id = message.chat.id # Telegram ID of the user
us_name = message.chat.first_name # Username of the user
if message.chat.type == 'private':
try:
cursor.execute(f"SELECT user_id from user_data WHERE user_id = {us_id}") # First check if user is in the database
records = cursor.fetchone()
bot.send_message(message.chat.id, f""
f"Hello, Welcome Back you're in our database\n"
)
except: # If user is not in the database...
db_table_val(user_id=us_id, user_name=us_name) # .... This will add it...
bot.send_message(message.chat.id, f"Welcome new user"
)
@Copyfoy

Copyfoy commented Feb 26, 2024

Copy link
Copy Markdown

Thank you very much

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment