Answer the question
In order to leave comments, you need to log in
How to fix such error when checking pyTelegramBotAPI subscription?
Hello. I am making a Telegram bot on PyTelegramBotAPI in which there is a subscription check for a telegram channel and encountered this error:
If one person writes the /start command and immediately after it some other person writes this command, then the first person has the "Check subscription" button will simply stop working (it will simply write "Thank you for subscribing to the channel", but will not redirect to the valid function, which in turn adds a person to the bot's database). For the second person, the "Check Subscription" button will work properly.
Code:
Command handler /start
@bot.message_handler(commands=['start'])
def start(message):
global usid
usid = message.chat.id
global usname
usname = message.from_user.username
try:
global referrer_id
referrer_id = message.text.split(' ')[1]
except IndexError:
referrer_id = 1005380696
sql.execute(f"SELECT chatid FROM users WHERE chatid = '{usid}'")
if sql.fetchone() is None:
marku = types.InlineKeyboardMarkup(row_width=2)
item1 = types.InlineKeyboardButton(" Проверить подписку", callback_data='sub_check')
marku.add(item1)
global res
res = bot.send_message(message.chat.id, " <b>Добро пожаловать</b>\n\n❗ Для <b>продолжения работы</b> с ботом вам необходимо <b>подписаться</b> на наш <b>оффициальный канал</b>: \n\nhttps://t.me/*ссылка на канал*", parse_mode='html', reply_markup=marku)
else:
bot.send_message(message.chat.id, " Вы в главном меню.", reply_markup=mm)
for value in sql.execute("SELECT * FROM users"):
print(value)
@bot.callback_query_handler(func=lambda call: True)
def callback_inline(call):
try:
if call.message:
if call.data == 'sub_check':
user_id = call.message.chat.id
group_id = "*айди группы*"
check = bot.get_chat_member(group_id, user_id)
if check.status == "member":
sql.execute(f"SELECT chatid FROM users WHERE chatid = '{usid}'")
if sql.fetchone() is None:
valid(call.message)
bot.send_message(call.message.chat.id, "✔ Благодарим вас за подписку на канал!\n\n❗ Если бот по каким-то причинам вам не отвечает - напишите /start.")
bot.delete_message(call.message.chat.id, res.message_id)
else:
bot.send_message(call.message.chat.id, "❗ Вы уже зарегистрированы.")
elif check.status == "creator":
sql.execute(f"SELECT chatid FROM users WHERE chatid = '{usid}'")
if sql.fetchone() is None:
valid(call.message)
bot.send_message(call.message.chat.id, "✔ Благодарим вас за подписку на канал!")
bot.delete_message(call.message.chat.id, res.message_id)
else:
bot.send_message(call.message.chat.id, "❗ Вы уже зарегистрированы.")
else:
bot.send_message(call.message.chat.id, "❌ Пожалуйста, проверьте подписаны ли вы на все каналы.")
def valid(message):
sql.execute(f"INSERT INTO users VALUES(?,?,?,?,?)", (usid, usname, 0, 0, referrer_id))
for value in sql.execute(f"SELECT * FROM users WHERE chatid = '{message.chat.id}'"):
print(f"Новый пользователь: @{value[1]}, referal: {value[4]}")
for value in sql.execute(f"SELECT * FROM users WHERE chatid = '{value[4]}'"):
print(value[1])
ref_balance = value[2]
print(ref_balance, value[1])
new_ref_balance = ref_balance + 2
print(new_ref_balance, value[1])
ref_count = value[3]
new_ref_count = ref_count + 1
print(new_ref_count, value[1])
bot.send_message(value[0],
f"➕ Вы пригласили <b>реферала</b>.\n\n Текущий баланс: <b>{new_ref_balance} рублей</b>\n\n Всего приглашено пользователей: <b>{new_ref_count}</b>",
parse_mode='html')
sql.execute(f"UPDATE users SET balance = {new_ref_balance} WHERE chatid = '{value[0]}'")
sql.execute(f"UPDATE users SET refcount = {new_ref_count} WHERE chatid = '{value[0]}'")
sql.execute(f"UPDATE info SET earned = earned+2")
db.commit()
bot.send_message(message.chat.id, f"➖ Вы успешно <b>зарегистрировались</b>\n\n➕ В данном <b>боте</b> вы сможете <b>заработать</b> на <b>привлечении рефералов</b>.", parse_mode='html', reply_markup=mm)
db.commit()
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question