Python Telepot bot inline keybard - python

I am building a bot in Python using Telepot. I am able to have it respond to commands but when i implement an inline keyboard i do not know how to call on them. I know it must be callbackquery but i cannot find how to implement it.
Any help would be appreciated.
import sys
import time
import telepot
from telepot.namedtuple import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton
def on_chat_message(msg):
content_type, chat_type, chat_id = telepot.glance(msg)
print('Chat Message:', content_type, chat_type, chat_id)
if content_type == 'text':
if msg['text'] == '/start':
bot.sendMessage(chat_id, 'Welcome to #UK_Cali Teleshop\n Created by JonSnow 2021',reply_markup = InlineKeyboardMarkup(inline_keyboard=[
[InlineKeyboardButton(text="Feedback",callback_data='a'), InlineKeyboardButton(text="You",callback_data='b'),InlineKeyboardButton(text="PGP",callback_data='c'), InlineKeyboardButton(text="Cunt",callback_data='d')],
[InlineKeyboardButton(text="Products",callback_data='e')]
]
))
bot.answerCallbackQuery(callback_query_id)
bot = telepot.Bot('1646167995:AAGsOwfjcryYYkoah69QJ6XGA7koUywmuRk')
print('Listening ...')
bot.message_loop({'chat': on_chat_message}, run_forever=True)
bot = telepot.Bot('TOKEN')

import time
import telepot
from telepot.loop import MessageLoop
from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton
TOKEN = "super secret bot token"
def on_chat_message(msg):
#here you handel messages and create the iniline keyboard
content_type, chat_type, chat_id = telepot.glance(msg)
keyboard = InlineKeyboardMarkup(inline_keyboard=[
[InlineKeyboardButton(text='button text', callback_data='callback query data for reconizing it')],
])
def on_callback_query(msg):
#here you handels callback querys,
#the event that are fired when user clickan inline keyboard'sbutton
query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')
#do something based on the callback query,
#to recognize the button pressed check query_data,
#that corresponds to he callback_data setted when creating the button
bot = telepot.Bot(TOKEN)
MessageLoop(bot, {'chat': on_chat_message,
'callback_query': on_callback_query}).run_as_thread()
while True:
time.sleep(10)

Related

Redirect messages automatically in Telegram

I want to make automation that gets a message from a group, that we'll call group A.
And send it into group B.
I should use Telegram API or Telegram BOTs to solve this?
And how i can solve this problem using python?
I was having this same problem and figured this out:
# imports
from telegram import Update
from telegram.ext import *
import telegram
from dotenv import load_dotenv
import os
# get the telegram bot api_key from environment file
load_dotenv()
API_KEY = os.getenv('API_KEY')
# you will need the groub_b_id saved as a global variable or
# in some other document
group_b_id = 1234567890
# create the bot, updater, and dispatcher
bot = telegram.Bot(token=API_KEY)
updater = Updater(API_KEY, use_context=True)
dp = updater.dispatcher
def get_chat_id(update: Update, context: CallbackContext):
# gets the chat_id of the current chat
global bot
chat_id = update.effective_chat.id
bot.send_message(chat_id, "This chat's id is: " + str(chat_id))
def auto_forward(update: Update, context: CallbackContext):
# automatically forwards messages from this chat to
# chat_b
global bot, group_b_id
chat_id = update.effective_chat.id
username = update.effective_message.from_user.name
chat_title = update.effective_message.chat.title
msg_txt = update.effective_message.text
bot.send_message(
group_b_id,
text=f"'{msg_txt}'\nwas just sent in chat {chat_title} by {username}"
)
# sets up the handlers
dp.add_handler(CommandHandler('get_chat_id', get_chat_id))
dp.add_handler(MessageHandler(Filters.text, auto_forward))
# Start the Bot
updater.start_polling()
updater.idle()
just make sure that you add the bot as an admin to both chats and this will work!

Telegram bot ConversationHandler ignores fallbacks

I have an issue with the Telegram bot (python-telegram-bot). I've made ConversationHandler, but the "fallbacks" won't work. Bot just ignores the "/stop " command. When I send "/stop" the bot sends me "First handler" instead of "GoodBye". What's wrong?
import os
import telegram
from telegram.ext import (ConversationHandler,
CommandHandler,
MessageHandler,
Filters,
Updater
)
from dotenv import load_dotenv
load_dotenv()
TELEGRAM_TOKEN = os.environ['TELEGRAM_TOKEN']
USER_ID = os.environ['USER_ID']
bot = telegram.Bot(token=TELEGRAM_TOKEN)
updater = Updater(token=TELEGRAM_TOKEN)
def start(update, context):
context.bot.send_message(chat_id=update.effective_chat.id,
text='hi')
return 1
def stop(update, context):
context.bot.send_message('Good Bye')
return ConversationHandler.END
def first_handler(update, context):
context.bot.send_message(chat_id=update.effective_chat.id,
text='First handler')
return 1
conv_handler = ConversationHandler(
entry_points=[CommandHandler('Start', start)],
states={
1: [MessageHandler(Filters.text, first_handler,
pass_user_data=True)],
},
fallbacks=[CommandHandler('stop', stop)]
)
dispatcher = updater.dispatcher
dispatcher.add_handler(conv_handler)
updater.start_polling()
updater.idle()
According to the documentation, the MessageHandler(Filters.text, ...) is handling all text messages, including the /stop command. However, fallbacks are only being triggered if none of the above handlers were able to deal with the message.
You may exclude commands from the MessageHandler:
MessageHandler(
Filters.text & (~ Filters.command),
first_handler,
)
The syntax for combining filters is documented here.

Telegram Bot get as User Input previous message

I'm experiencing a small issue with the library python-telegram-bot.
So this is my code:
from __future__ import unicode_literals
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from telegram.ext import CommandHandler, CallbackQueryHandler, CallbackContext
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, ReplyKeyboardMarkup
from telegram import Update
from telegram import Bot
import telegram
import os
import datetime
import sqlite3
import traceback
import re
import data
def start(update, context):
chatid = update.message.chat_id
if data.user_exist(chatid) == True:
update.message.reply_text('Choiche wallet', reply_markup=wallet_handler(chatid, update, context))
if data.user_exist(chatid) == False:
update.message.reply_text('Add wallet')
add_wallet(chatid, update, context)
def wallet_handler(chatid, update, context):
kb = []
for w in data.fetch_wallet(chatid):
s = w[0:10]
kb.append([InlineKeyboardButton(s, callback_data=w)])
kb.append([InlineKeyboardButton('Add Wallet', callback_data='add')])
kb.append([InlineKeyboardButton('Delete Wallet', callback_data='delete')])
return InlineKeyboardMarkup(kb)
def add_wallet(chatid, update, context):
regex = re.compile(r"/^(?:0x)[A-Z0-9]{15}$/")
update.message.reply_text(text='Insert a wallet address please')
address = update.message.text
print(address)
if re.fullmatch(regex, address):
print('okay')
else:
print('nooo')
return
def main():
update= Updater('token', use_context=True)
bot = Bot('token')
disp=update.dispatcher
disp.add_handler(CommandHandler('start', start))
disp.add_handler(MessageHandler(Filters.regex('/^(?:0x)[A-Z0-9]{15}$/'), add_wallet, run_async=True))
update.start_polling()
update.idle()
if __name__=='__main__':
main()
When the user send the /start command, the function user_exist() check a determined condition. If the function returns false, then the bot should wait for user input (triggering the function add_wallet()).
But when I try this code, the add_wallet() function takes as user input the previous message /start and doesn't wait for the user input.
How to fix it? Thanks

Flask, change telegram bot token in runtime

This is how I start the bot now:
""" Bot logic """
from flask import request
from shopbot_crm import shopbot_crm_bp
import telebot
from telebot import types
from telebot import apihelper
import secrets
from models import db, TgBot
secret = secrets.token_urlsafe(32)
bot = telebot.TeleBot('token', threaded=False)
bot.remove_webhook()
time.sleep(1)
bot.set_webhook(url="https://mywebhook.com/bot_panel/bot/{}".format(secret))
apihelper.ENABLE_MIDDLEWARE = True
#shopbot_crm_bp.route('/bot/{}'.format(secret), methods=["POST"])
def webhook():
bot.process_new_updates([telebot.types.Update.de_json(request.stream.read().decode("utf-8"))])
return "ok", 200
#shopbot_crm_bp.route('/bot/reload', methods=["GET"])
def bot_reload():
#Can I somehow change the token from here?
#bot.message_handler(content_types=['text'])
def hello(message):
bot.send_message(message.chat.id, 'Hello')
In my application, the user should be able to change the current token to the bot.
Question:
How can I change this token to another and re-create the webhook in runtime?

How do you make the python bot click on the button in the telegram bot

I want to make a bot click for Telegram. The problem is I'm confused about how I clicked it using my code, I tried it but it still failed and the bot didn't click, what data should be posted so that the bot clicks on the telegram bot. I need your help. This is my source code :
from telethon import TelegramClient, events, sync
from telethon.tl.functions.messages import GetHistoryRequest, GetBotCallbackAnswerRequest
api_id = 974119
api_hash = 'a483ea002564cdaa0499a08126abe4a3'
client = TelegramClient('session_name', api_id, api_hash)
client.start()
channel_username = 'GOOGLE'
channel_entity = client.get_entity(channel_username)
posts = client(GetHistoryRequest(
peer=channel_entity,
limit=1,
offset_date=None,
offset_id=0,
max_id=0,
min_id=0,
add_offset=0,
hash=0))
messageId = posts.messages[0].id
client(GetBotCallbackAnswerRequest(
channel_username,
messageId,
data=posts.messages[0].reply_markup.rows[0].buttons[0]))
client.disconnect()
The button that must be clicked is KeyboardButtonUrl or 🔎 Go to website :
reply_markup=ReplyInlineMarkup(
rows=[
KeyboardButtonRow(
buttons=[
KeyboardButtonUrl(
text='🔎 Go to website',
url='https://www.google.com'
),
]
),
KeyboardButtonRow(
buttons=[
KeyboardButtonCallback(
text='🛑 Report',
data=b'{"name":"ReportClick","id":"120326622"}'
),
KeyboardButtonCallback(
text='⏩ Skip',
data=b'{"name":"SkipClick","id":"120326622"}'
),
]
),
]
),
You should not use client.get_entity() in this case, it's not necessary.
You should use client.get_messages(), not GetHistoryRequest.
You should use message.click(), not GetBotCallbackAnswerRequest.
So your code would be:
from telethon import TelegramClient, sync
api_id = ...
api_hash = ...
client = TelegramClient('session_name', api_id, api_hash)
messages = client.get_messages('GOOGLE')
messages[0].click()
This should be enough to click the first button of the last message in the channel.
sender = await event.get_sender()
messages = await client.get_messages(sender.username)
await messages[0].click(0)
This will click the first button in the message. You could also click(row, column), using some text such as click(text='👍') or even the data directly click(data=b'payload').

Categories

Resources