M
M
Megach2020-08-15 17:13:42
Python
Megach, 2020-08-15 17:13:42

How to write person id from telegram to sqlite3 database using pyTelegramBotAPI?

Hello

, I need when a person writes messages to the bot, the bot recognizes his telegram ID and writes it to the database

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
alekssamos, 2020-08-15
@Megach

import sqlite3

# Создаём базу,
# если её ещё не существует
with sqlite3.connect("tg.sqlite") as conn:
  cursor = conn.cursor()
  cursor.execute("""
  CREATE TABLE IF NOT EXISTS users
  (CHAT_ID INTEGER, name TEXT)
  """)

# Теперь запишем:
chat_id = 123 # допустим
text = "Vasya"
with sqlite3.connect("tg.sqlite") as conn:
  cursor.execute("INSERT INTO users VALUES (?,?)", (chat_id, text))
  conn.commit()

# И теперь прочитаем.
chat_id = 123 # допустим
# У нас есть только chat_id,
# получим имя из нашей базы:
with sqlite3.connect("tg.sqlite") as conn:
  sql = "SELECT name FROM users WHERE chat_id=?"
  cursor.execute(sql, [(chat_id)])
  name = cursor.fetchone()[0]
  print(f"Пользователя с айди {chat_id} зовут {name}.")
# всё!

I
iredoff, 2020-08-15
@iredoff

It's simple, to get the user's id, use callback.chat.id in the message event. And then you can write to the database

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question