Telegram Bot get as User Input previous message - python

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

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.

Python Telepot bot inline keybard

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)

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?

make telegram bot using python

I'm trying to make a telegram bot using python, but for some reason it doesn't post the info to the telegram. my code is supposed to send a data frame to telegram as a table but it returns noting(even a error) when I call it from telegram.
from telegram.ext import Updater, InlineQueryHandler, CommandHandler
import requests
import re
import pandas as pd
def get_data():
data = pd.read_excel('C:/Users/admin/Desktop/data.xlsx')# opening xlsx file as the input
data = data.to_string(columns = ['c.1', 'c.2'], index = False, header = True, line_width = 70, justify = 'left')
return data
def result(bot, update):
data = get_data()
chat_id = update.message.chat_id
bot.send_message(chat_id=chat_id, table=data)
bot.send_photo(chat_id=chat_id, photo=data)
def main():
updater = Updater('Token key')
dp = updater.dispatcher
dp.add_handler(CommandHandler('result',result))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
Did you try to use the new CallbackContext? There should be an message linking to this page: https://github.com/python-telegram-bot/python-telegram-bot/wiki/Transition-guide-to-Version-12.0) when starting the bot. There it says:
Now on to the bulk of the change. You wanna change all your callback functions from the following:
def start(bot, update, args, job_queue):
# Stuff here
to the new style using CallbackContext
def start(update: Update, context: CallbackContext):
# Stuff here
# args will be available as context.args
# jobqueue will be available as context.jobqueue
I got it to work with a minimal example like this:
from telegram.ext import Updater, InlineQueryHandler, CommandHandler
def result(update, context):
print('result called')
data = 'mydata'
update.message.reply_text(data)
def main():
updater = Updater('Token', use_context=True)
dp = updater.dispatcher
dp.add_handler(CommandHandler('result',result))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
P.S.: You don't seem to use the requests and re from the imports.

Categories

Resources