Python Telegram bot - second InLineKeyboard not working - python

I made telegram bot which works fine except the second InLineKeyboard (keyboard2 in the relevant code below). Can you provide any hints why? Thanks!
#bot.message_handler(content_types=['text'])
def get_text_messages(message):
if message.text == "start":
keyboard = types.InlineKeyboardMarkup()
btn1 = types.InlineKeyboardButton(text="1", callback_data="1")
...
btn10 = types.InlineKeyboardButton(text="10", callback_data="10")
keyboard.row(btn1, btn2, btn3, btn4, btn5)
keyboard.row(btn6, btn7, btn8, btn9, btn10)
bot.send_message(
message.chat.id, "some text", reply_markup=keyboard)
else:
keyboard2 = types.InlineKeyboardMarkup()
btn11 = types.InlineKeyboardButton(text="Yes", callback_data="yes")
btn12 = types.InlineKeyboardButton(text="No", callback_data="no")
keyboard2.add(btn11, btn12)
bot.send_message(message.from_user.id, "some text", reply_markup=keyboard2)
#bot.callback_query_handler(func=lambda call: True)
def callback_inline(call):
if call.message:
if call.data == "1":
img = open('1.jpg', 'rb')
bot.send_photo(chat_id=call.message.chat.id, photo=img, reply_markup=keyboard)
img.close()
#Nine more buttons here
elif call.data == "yes":
bot.send_message(message.chat.id, "some text", reply_markup=keyboard)
elif call.data == "no":
bot.send_message(message.from_user.id, "some text")

Related

telegram bot reply message for buttons

recently i created a telegram bot using python and i added keyboard button features to the bot. However, i am having difficulties in getting replies from bot to the buttons users choose.
button7 = KeyboardButton('About Us',request_contact= False)
keyboard2 = ReplyKeyboardMarkup(resize_keyboard = True, one_time_keyboard = True).row(button7)
#dp.message_handler(commands=['info'])
async def mood(message: types.Message):
await message.reply('Do you wish to know about us??', reply_markup=keyboard2)
In this case, i created a button named "About Us" and i want the bot to open a url using webbrowser.open if the user click on that button. Can anyone help me solving this problem?
Try it:
markup = types.InlineKeyboardMarkup()
button1 = types.InlineKeyboardButton(text='Ukraine', url="https://en.wikipedia.org/wiki/Ukraine", callback_data='1')
markup.add(button1)
bot.send_message(message.from_user.id, 'Do you know?, parse_mode='Markdown', reply_markup=markup)
Text (inline button)
from aiogram import Bot, Dispatcher, executor, types
bot = Bot(token='token')
dp = Dispatcher(bot)
#dp.message_handler(commands=['start'])
async def welcome(message: types.Message):
markup = types.InlineKeyboardMarkup()
button1 = types.InlineKeyboardButton(text='Ukraine', url="https://en.wikipedia.org/wiki/Ukraine", callback_data='1')
button2 = types.InlineKeyboardButton(text='Hi bot!', callback_data="1")
markup.add(button1, button2)
await bot.send_message(message.from_user.id, "Do you know?", parse_mode="Markdown", reply_markup=markup)
#dp.callback_query_handler(lambda call: True)
async def sendText(call: types.CallbackQuery):
msg = ""
if call.data == "1":
msg = "Hi, programmer!"
await call.message.edit_text(msg)
if __name__ == '__main__':
executor.start_polling(dp, skip_updates=True)

Telebot, Python and InlineKeyboard

Im triyng to make filter inside inlinekeyboard, in short:
markup = types.InlineKeyboardMarkup()
button_4 = types.InlineKeyboardButton('Да, все верно', callback_data = 'yes')
button_5 = types.InlineKeyboardButton('Нет, нужно изменить', callback_data = 'no')
markup.add(button_4, button_5)
bot.send_message(message.chat.id, 'Введеные данные верны?', reply_markup = markup)
#bot.callback_query_handler(func = lambda call: True)
def answer(call):
if call.data == 'yes':
print('GOT IT')
but nothing happend, i don't see "GOT IT" in terminal (btw i used it in same code at the begin and it works...)
Try to Print callBack data:
#bot.message_handler(commands=["start"])
key = types.InlineKeyboardMarkup()
key.add(types.InlineKeyboardButton('Да, все верно', callback_data='yes'))
key.add(types.InlineKeyboardButton('Нет, нужно изменить', callback_data='no'))
bot.send_message(message.chat.id, 'Введеные данные верны?', reply_markup=markup)
#bot.callback_query_handler(func=lambda call: call.data)
def answer(call):
print(call.data)

The telegram bot does not work(pyQiwi or aiogram)

Hello everyone I wrote a bot for a freelance tutorial order, the bot responds to messages, but there is a problem with payment, after entering the amount of replenishment, the bot does not respond, maybe I made a mistake somewhere?
main.py code
import logging
from aiogram import Bot, Dispatcher, executor, types
import config as cfg
import markups as nav
logging.basicConfig(level=logging.INFO)
import logging
from aiogram import Bot, Dispatcher, executor, types
import config as cfg
import markups as nav
from db import Database
from pyqiwip2p import QiwiP2P
import random
logging.basicConfig(level=logging.INFO)
bot = Bot(token=cfg.TOKEN)
dp = Dispatcher(bot)
db = Database("database.db")
p2p = QiwiP2P(auth_key=cfg.QIWI_TOKEN)
def is_number(_str):
try:
int(_str)
return True
except ValueError:
return False
#dp.message_handler(commands=['start'])
async def command_start(message: types.Message):
if message.chat.type == 'private':
if not db.user_exists(message.from_user.id):
db.add_user(message.from_user.id)
await bot.send_message(message.from_user.id, "Здравствуй дорогой {0.first_name}!\n\nТвой процент удачи сегодня: 99%\n"
f"\n💳Ваш баланс: {db.user_money(message.from_user.id)} руб".format(message.from_user), reply_markup=nav.mainMenu)
#dp.message_handler()
async def command_start(message: types.Message):
if message.text == 'ST':
await bot.send_message(message.from_user.id, '🕹️Купить читы')
elif message.text == '🕹️Купить читы':
await bot.send_message(message.from_user.id, '🤖Выберите игру!', reply_markup = nav.ChFoGaMeMenu)
elif message.text == '📰Hot Новости':
await bot.send_message(message.from_user.id, '🤖Выберите дату!', reply_markup = nav.newsMenu)
elif message.text == '🔥️Лайфхаки дня':
await bot.send_message(message.from_user.id, '🤖Выберите жанр игры!', reply_markup=nav.LiHaMenu)
elif message.text == '🤖О боте':
await bot.send_message(message.from_user.id, '🤖Хоешь узнать обо мне?!', reply_markup=nav.aboutthebotMenu)
elif message.text == '👤Профиль':
await bot.send_message(message.from_user.id, '💬Ваш аккаунт'.format(message.from_user), reply_markup=nav.myaccMenu)
elif message.text == '🔙Главное меню':
await bot.send_message(message.from_user.id, '🔙Вы в главном меню', reply_markup=nav.mainMenu)
#Читы для игр
elif message.text == '🎁CS-GO':
await bot.send_message(message.from_user.id, '\n💳Оплатить товар [🎁CS-GO] 110₽'
'\n'
'\n💰Оплата Qiwi/Сбер/Тинькофф', reply_markup=nav.buyCSMenu)
elif message.text == '🎁Dota2':
await bot.send_message(message.from_user.id, '\n💳Оплатить товар [🎁Dota2] 110₽'
'\n'
'\n💰Оплата Qiwi/Сбер/Тинькофф', reply_markup=nav.buyDota2Menu)
elif message.text == '🎁Call Of Duty:Black Ops':
await bot.send_message(message.from_user.id, '\n💳Оплатить товар [🎁Call Of Duty:Black Ops] 110₽'
'\n'
'\n💰Оплата Qiwi/Сбер/Тинькофф', reply_markup=nav.buyCallOfDutyMenu)
elif message.text == '🎁PUBG':
await bot.send_message(message.from_user.id, '\n💳Оплатить товар [🎁PUBG] 110₽'
'\n'
'\n💰Оплата Qiwi/Сбер/Тинькофф', reply_markup=nav.buyPUBGMenu)
elif message.text == '🎁Standoff2':
await bot.send_message(message.from_user.id, '\n💳Оплатить товар [🎁Standoff2] 110₽'
'\n'
'\n💰Оплата Qiwi/Сбер/Тинькофф', reply_markup=nav.buyStandoff2Menu)
elif message.text == '🔙Главное меню':
await bot.send_message(message.from_user.id, '🔙Вы в главном меню', reply_markup=nav.ChFoGaMeMenu)
#Новости для игр
elif message.text == '📋Today':
await bot.send_message(message.from_user.id, '📋Today', reply_markup=nav.newsTMenu)
elif message.text == '📋Yesterday':
await bot.send_message(message.from_user.id, '📋Yesterday', reply_markup=nav.newsYEMenu)
elif message.text == '🔙Главное меню':
await bot.send_message(message.from_user.id, '🔙Вы в главном меню', reply_markup=nav.ChFoGaMeMenu)
#Лайфхак для игр
elif message.text == '🔥Шутеры':
await bot.send_message(message.from_user.id, '🔥Лайфхаки для [Шутеров] читай в Telegraph', reply_markup=nav.newsShootMenu)
elif message.text == '🔥ММОРПГ':
await bot.send_message(message.from_user.id, '🔥Лайфхаки для [ММОРПГ] читай в Telegraph', reply_markup=nav.newsMMORPGMenu)
elif message.text == '🔥Стратегии':
await bot.send_message(message.from_user.id, '🔥Лайфхаки для [Стратегии] читай в Telegraph', reply_markup=nav.newsStrategyMenu)
elif message.text == '🔥MMO Action[скоро!]':
await bot.send_message(message.from_user.id, '🔥Лайфхаки для [MMO Action] читай в Telegraph', reply_markup=nav.newsMMOActionMenu)
elif message.text == '🔙Главное меню':
await bot.send_message(message.from_user.id, '🔙Вы в главном меню', reply_markup=nav.ChFoGaMeMenu)
#О боте для игр
elif message.text == '🤖Кто я?':
await bot.send_message(message.from_user.id, '🤖Основная информация о боте указана в telegraph!', reply_markup=nav.newsWhoiambMenu)
elif message.text == '📄Соглашение':
await bot.send_message(message.from_user.id, '📄Основная информация о пользовательском соглашении указана в telegraph!', reply_markup=nav.newsSoglbMenu)
elif message.text == '🔙Главное меню':
await bot.send_message(message.from_user.id, '🔙Вы в главном меню', reply_markup=nav.ChFoGaMeMenu)
#Профиль игрока
elif message.text == '💥Главное':
await bot.send_message(message.from_user.id, '\n💬Ваш аккаунт: {0.first_name}'
'\n'
'\n🧾Количество покупок: '
'\n'
f'\n💳Ваш баланс: {db.user_money(message.from_user.id)} руб.'.format(message.from_user), reply_markup=nav.myaccMenu)
elif message.text == '🧾Мои покупки':
await bot.send_message(message.from_user.id, '\n🧾Ваши покупки: '.format(message.from_user), reply_markup=nav.myaccMenu)
elif message.text == '💳Баланс':
await bot.send_message(message.from_user.id, f'\n💳Ваш баланс: {db.user_money(message.from_user.id)} руб.'.format(message.from_user), reply_markup=nav.topUpMenu)
elif message.text == '🔙Главное меню':
await bot.send_message(message.from_user.id, '🔙Вы в главном меню', reply_markup=nav.ChFoGaMeMenu)
#dp.message_handler()
async def bot_mess(message: types.Message):
if is_number(message.text):
message_money = int(message.text)
if message_money >= 5:
comment = str(message.from_user.id) + "_" + str(random.randint(1000, 9999))
bill = p2p.bill(amount=message_money, lifetime=15, comment=comment)
db.add_check(message.from_user.id, message_money, bill.bill_id)
await bot.send_message(message.from_user.id, f"Вам нужно отправить {message_money} руб. на наш счет QIWI\nСсылку: {bill.pay_url}\nУказав комментарий к оплате: {comment}", reply_markup=nav.buy_menu(url=bill.pay_url, bill=bill.bill_id))
else:
await bot.send_message(message.from_user.id, "Минимальная сумма для пополнения 5 руб.")
else:
await bot.send_message(message.from_user.id, "Введите целое число")
#dp.callback_query_handler(text="top_up")
async def top_up(callback: types.CallbackQuery):
await bot.delete_message(callback.from_user.id, callback.message.message_id)
await bot.send_message(callback.from_user.id, "Введите сумму для пополнения!")
#dp.callback_query_handler(text_contains="check_")
async def check(callback: types.CallbackQuery):
bill = str(callback.data[6:])
info = db.get_check(bill)
if info != False:
if str(p2p.check(bill_id=bill).status) == "PAID":
user_money = db.user_money(callback.from_user.id)
money = int(info[2])
db.set_money(callback.from_user.id, user_money+money)
await bot.send_message(callback.from_user.id, "Ваш счет пополнен! Напишите /start")
db.delete_check(bill)
else:
await bot.send_message(callback.from_user.id, "Вы не оплатили счет!", reply_markup=nav.buy_menu(False, bill=bill))
else:
await bot.send_message(callback.from_user.id, "Счет не найден")
if __name__ == '__main__':
executor.start_polling(dp, skip_updates=True)
config.py code
TOKEN = "MyToken"
QIWI_TOKEN = "MyToken"
murkaps.py code
from aiogram.types import ReplyKeyboardMarkup, KeyboardButton
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
btnMain = KeyboardButton('🔙Главное меню')
# ---Main Menu---
btnBuyCheat = KeyboardButton('🕹️Купить читы')
btnNews = KeyboardButton('📰Hot Новости')
btnLifeHack = KeyboardButton('🔥️Лайфхаки дня')
btnMyacc = KeyboardButton('👤Профиль')
btnAboutTheBot = KeyboardButton('🤖О боте')
mainMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnBuyCheat, btnNews, btnLifeHack, btnMyacc, btnAboutTheBot)
btnTopUp = InlineKeyboardButton(text="Пополнить", callback_data="top_up")
topUpMenu = InlineKeyboardMarkup(row_width=1)
topUpMenu.insert(btnTopUp)
# ---Cheat For Game Menu---
btnCSGO = KeyboardButton('🎁CS-GO')
btnDota2 = KeyboardButton('🎁Dota2')
btnCODBO = KeyboardButton('🎁Call Of Duty:Black Ops')
btnPUBG = KeyboardButton('🎁PUBG')
btnST2 = KeyboardButton('🎁Standoff2')
ChFoGaMeMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnCSGO, btnDota2, btnCODBO, btnPUBG, btnST2, btnMain)
# ---Cheat For Game Menu---
btnToday = KeyboardButton('📋Today')
btnYetday = KeyboardButton('📋Yesterday')
newsMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnToday, btnYetday, btnMain)
# ---Lifehack for Game Menu---
btnShoot = KeyboardButton('🔥Шутеры')
btnMMORPG = KeyboardButton('🔥ММОРПГ')
btnStrateg = KeyboardButton('🔥Стратегии')
btnMMOA = KeyboardButton('🔥MMO Action[скоро!]')
LiHaMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnShoot, btnMMORPG, btnStrateg, btnMMOA, btnMain)
# ---About The Bot Menu---
btnWhoiam = KeyboardButton('🤖Кто я?')
btnSogl = KeyboardButton('📄Соглашение')
aboutthebotMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnWhoiam, btnSogl, btnMain)
# ---Buy Cheat For 🎁CS-GO Menu---
btnCSBuy = KeyboardButton('💳Оплатить\n[🎁CS-GO]')
buyCSMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnCSBuy, btnMain)
# ---Buy Cheat For 🎁Dota2 Menu---
btnDota2Buy = KeyboardButton('💳Оплатить\n[🎁Dota2]')
buyDota2Menu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnDota2Buy, btnMain)
# ---Buy Cheat For 🎁Call Of Duty:Black Ops Menu---
btnCallOfDutyBuy = KeyboardButton('💳Оплатить\n[🎁Call Of Duty:Black Ops]')
buyCallOfDutyMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnCallOfDutyBuy, btnMain)
# ---Buy Cheat For 🎁PUBG Menu---
btnPUBGBuy = KeyboardButton('💳Оплатить\n[🎁PUBG]')
buyPUBGMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnPUBGBuy, btnMain)
# ---Buy Cheat For 🎁Standoff2 Menu---
btnStandoff2Buy = KeyboardButton('💳Оплатить\n[🎁Standoff2]')
buyStandoff2Menu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnStandoff2Buy, btnMain)
# ---NewsToday Menu---
btnToday = KeyboardButton('📋Читать')
newsTMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnToday, btnMain)
# ---NewsYesterday Menu---
btnYesToday = KeyboardButton('📋Читать')
newsYEMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnYesToday, btnMain)
# ---🔥Шутеры Menu---
btnShoot = KeyboardButton('🔥Читать')
newsShootMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnShoot, btnMain)
# ---🔥ММОРПГ Menu---
btnMMORPG = KeyboardButton('🔥Читать')
newsMMORPGMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnMMORPG, btnMain)
# ---🔥Стратегии---
btnStrategy = KeyboardButton('🔥Читать')
newsStrategyMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnStrategy, btnMain)
# ---🔥MMO Action[скоро!] Menu---
btnMMOActionToday = KeyboardButton('🔥Читать')
newsMMOActionMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnMMOActionToday, btnMain)
# ---About Bot Menu---
btnWhoiamb = KeyboardButton('📋Читать')
newsWhoiambMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnWhoiamb, btnMain)
# ---Bot Agreement Menu---
btnSoglb = KeyboardButton('📋Читать')
newsSoglbMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnSoglb, btnMain)
# ---Profell Menu---
btnGlavn = KeyboardButton('💥Главное')
btnChek = KeyboardButton('🧾Мои покупки')
btnBalans = KeyboardButton('💳Баланс')
myaccMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnGlavn, btnChek, btnBalans, btnMain)
# ---Popolnit Menu---
def buy_menu(isUrl = True, url="", bill=""):
qiwiMenu = InlineKeyboardMarkup(row_width=1)
if isUrl:
btnUrlQIWI = InlineKeyboardButton(text="Ссылка на оплату", url=url)
qiwiMenu.insert(btnUrlQIWI)
btnChekQIWI = InlineKeyboardButton(text="Проверить оплату", callback_data="check_"+bill)
qiwiMenu.insert(btnChekQIWI)
return qiwiMenu
db.py code
import _sqlite3
class Database:
def __init__(self, db_file):
self.connection = _sqlite3.connect(db_file)
self.cursor = self.connection.cursor()
def user_exists(self, user_id):
with self.connection:
result = self.cursor.execute("SELECT * FROM users WHERE 'user_id' = ?", (user_id,)).fetchall()
return bool(len(result))
def add_user(self, user_id):
with self.connection:
return self.cursor.execute("INSERT INTO users ('user_id') VALUES (?)", (user_id,))
def user_money(self, user_id):
with self.connection:
result = self.cursor.execute("SELECT money FROM users WHERE user_id = ?", (user_id,)).fetchmany(1)
return int(result[0][0])
def set_money(self, user_id, user_money):
with self.connection:
return self.cursor.execute("UPDATE 'users' SET money = ? WHERE 'user_id' = ?", (user_money, user_id))
def add_check(self, user_id, money, bill_id):
with self.connection:
return self.cursor.execute("INSERT INTO 'check' ('user_id', 'money', 'bill_id') VALUES (?,?,?)", (user_id, money, bill_id,))
def get_check(self, bill_id):
with self.connection:
result = self.cursor.execute("SELECT * FROM 'check' WHERE bill_id = ?", (bill_id,)).fetchmany(1)
if not bool(len(result)):
return False
return result[0]
def delete_check(self, bill_id):
with self.connection:
return self.cursor.execute("DELETE FROM `check` WHERE `bill_id` = ?", (bill_id,))
I could not find a solution to the problem, can someone tell me
Try using states:
from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.dispatcher import FSMContext
from aiogram.contrib.fsm_storage.memory import MemoryStorage
dp = Dispatcher(bot, storage=MemoryStorage())
class Payment(StatesGroup):
wait_sum = State()
#dp.callback_query_handler(text="top_up")
async def top_up(callback: types.CallbackQuery):
await bot.delete_message(callback.from_user.id, callback.message.message_id)
await bot.send_message(callback.from_user.id, "Введите сумму для пополнения!")
await Payment.wait_sum.set()
#dp.message_handler(state=Payment.wait_sum)
async def bot_mess(message: types.Message, state: FSMContext):
#Your function for billing
#After user gave you the number:
await state.finish()

Repeat action on button click in telebot module

I'm implementing a simple function in Python, but it doesn't work
Function:
# Рандомное число с кнопкой
#bot.message_handler(content_types=['text'], commands=['get_number'])
def get_number(message):
number = random.randint(0, 1000)
markup = types.InlineKeyboardMarkup()
item_yes = types.InlineKeyboardButton('Да', callback_data='yes')
item_no = types.InlineKeyboardButton('Нет', callback_data='no')
markup.row(item_yes, item_no)
bot.send_message(message.chat.id, f"<i><b>Ваше число:</b></i>\n{number}\n\nЗагадать еще раз?", reply_markup=markup,
parse_mode='html')
# Реакция на нажатие кнопки
#bot.callback_query_handler(func=lambda call: True)
def answer(call, message):
if call.data == 'yes':
pass
elif call.data == 'no':
pass
Tell me how to make it so that when you click the "Yes" button, the function is executed when you click it again, when you click "No", it stops accordingly.
I believe you can change your method:
def answer(call, message):
for
def handle_query(call):

How to send a message when click in an InlineKeyboardButton (Telegram & Python)

I'm using TelegramBotAPI library to create a telegram bot in python.
I have this code to show an Inline Keyboard
def gen_markup():
markup = InlineKeyboardMarkup()
markup.row_width = 2
markup.add(InlineKeyboardButton("Yes", callback_data="cb_yes"),
InlineKeyboardButton("No", callback_data="cb_no"))
return markup
And after a function to see this keyboard when you send a command.
I have also this code to do an action when press on a button.
#bot.callback_query_handler(func=lambda call: True)
def send_welcome(call):
if call.data == "cb_yes":
bot.answer_callback_query(call.id, "YES")
elif call.data == "cb_no":
bot.send_message(call.id, "NO")
This only show the text on the screen and after some seconds it disappear. How can I send instead a text message?
Thanks
CallbackQuery contains the message object which holds chat id that can be used with send_message()
#bot.callback_query_handler(func=lambda call: True)
def callback_query(call):
if call.data == "cb_yes":
bot.answer_callback_query(call.id, "Answer is Yes")
elif call.data == "cb_no":
bot.send_message(call.message.chat.id, "This is a message")

Categories