Support
Quality
Security
License
Reuse
kandi has reviewed python-telegram-bot and discovered the below as its top functions. This is intended to give you an instant insight into python-telegram-bot implemented functionality, and help decide if they suit your requirements.
We have made you a wrapper you can't refuse
python-telegram-bot: Pass arguments to the bot
import os
import telegram
from telegram.ext import Updater, CommandHandler
# --- init ---
TOKEN = os.getenv('TELEGRAM_TOKEN')
updater = Updater(token=TOKEN, use_context=True)
dispatcher = updater.dispatcher
# --- commands ---
def start(update, context):
print('text:', update.message.text) # /start something
print('args:', context.args) # ['something']
dispatcher.add_handler(CommandHandler('start', start))
# --- start ---
updater.start_polling()
updater.idle()
How I can do a send message task inside a dispatcher.run_async() using python-telegram-bot?
dispatcher.run_async(myFunction, updater.bot)
def myfunction(bot):
bot.send_message(text='Hello, World',chat_id=123456789)
import telegram
from telegram.ext import Updater
def myfunction(bot):
bot.send_message(text='Hello, World',chat_id=123456789)
def main():
"""Start the bot."""
# Create the Updater and pass it your bot's token.
updater = Updater("<MY-BOT-TOKEN>")
# Get the dispatcher to register handlers
dispatcher = updater.dispatcher
dispatcher.run_async(myfunction, updater.bot)
# Start the Bot
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
-----------------------
dispatcher.run_async(myFunction, updater.bot)
def myfunction(bot):
bot.send_message(text='Hello, World',chat_id=123456789)
import telegram
from telegram.ext import Updater
def myfunction(bot):
bot.send_message(text='Hello, World',chat_id=123456789)
def main():
"""Start the bot."""
# Create the Updater and pass it your bot's token.
updater = Updater("<MY-BOT-TOKEN>")
# Get the dispatcher to register handlers
dispatcher = updater.dispatcher
dispatcher.run_async(myfunction, updater.bot)
# Start the Bot
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
How can I continue a nested conversation in a separate file
import src.main from main
if '__name__' == '__main__':
main()
How to send Django model object's details as answer according to the user's choice of InlineKeyboardButton?
filename = 'path_until_media_folder' + str(obj.img.url)
update.callback_query.bot.send_photo(update.effective_chat.id, photo=open(filename, 'rb'))
Python Telegram Bot Read Large Message
updater = Updater(token='XXXXXXXXXXXXXXXXXX')
dispatcher = updater.dispatcher
all_message = {
message_id = 0
text = ""
}
def runMe(update, context):
global all_message
if update.message.message_id == all_message["message_id"]:
received_message = update.message.text
all_message["text"] += received_message
print("Received message with length %d" % len(received_message))
# Save (full) message to file
else:
all_message["message_id"] = update.message.message_id
all_message["text"] += received_message
arg_handler = MessageHandler(Filters.text, runMe)
dispatcher.add_handler(arg_handler)
Can you trigger a command from another in telegram bot?
def button(update: Update, context: CallbackContext) -> None:
"""Parses the CallbackQuery and updates the message text."""
query = update.callback_query
# CallbackQueries need to be answered, even if no notification to the user is needed
# Some clients may have trouble otherwise. See https://core.telegram.org/bots/api#callbackquery
query.answer()
query.edit_message_text(text=f"Selected option: {query.data}")
help_command(update, context)
def help_command(update: Update, context: CallbackContext) -> None:
"""Displays info on how to use the bot."""
# update.message.reply_text("Use /start to test this bot.")
context.bot.send_message(update.effective_user.id, "Use /start to test this bot.")
def help_command(update: Update, context: CallbackContext) -> None:
"""Displays info on how to use the bot."""
if hasattr(update.message, "reply_text"):
update.message.reply_text("Use /start to test this bot.")
else:
context.bot.send_message(update.effective_user.id, "Use /start to test this bot.")
-----------------------
def button(update: Update, context: CallbackContext) -> None:
"""Parses the CallbackQuery and updates the message text."""
query = update.callback_query
# CallbackQueries need to be answered, even if no notification to the user is needed
# Some clients may have trouble otherwise. See https://core.telegram.org/bots/api#callbackquery
query.answer()
query.edit_message_text(text=f"Selected option: {query.data}")
help_command(update, context)
def help_command(update: Update, context: CallbackContext) -> None:
"""Displays info on how to use the bot."""
# update.message.reply_text("Use /start to test this bot.")
context.bot.send_message(update.effective_user.id, "Use /start to test this bot.")
def help_command(update: Update, context: CallbackContext) -> None:
"""Displays info on how to use the bot."""
if hasattr(update.message, "reply_text"):
update.message.reply_text("Use /start to test this bot.")
else:
context.bot.send_message(update.effective_user.id, "Use /start to test this bot.")
Command handler Telethon
@client.on(events.NewMessage(pattern=r'!raw (\w+)'))
async def handler(event):
...
arg = event.pattern_match.group(1)
print(arg) # first word
parts = event.raw_text.split()
if len(parts) > 1:
arg = parts[1]
-----------------------
@client.on(events.NewMessage(pattern=r'!raw (\w+)'))
async def handler(event):
...
arg = event.pattern_match.group(1)
print(arg) # first word
parts = event.raw_text.split()
if len(parts) > 1:
arg = parts[1]
-----------------------
@client.on(events.NewMessage(pattern=r'!raw (\w+)'))
async def handler(event):
...
arg = event.pattern_match.group(1)
print(arg) # first word
parts = event.raw_text.split()
if len(parts) > 1:
arg = parts[1]
Why do I get 'MySQL server has gone away' after running a Telegram bot for some hours?
SET SESSION wait_timeout = ...
-----------------------
from django.db import close_old_connections
try:
#do your long running operation here
except django.db.utils.OperationalError:
close_old_connections()
#do your long running operation here
from channels.db import database_sync_to_async
async def connect(self):
self.username = await database_sync_to_async(self.get_name)()
def get_name(self):
return User.objects.all()[0].name
@database_sync_to_async
def get_name(self):
return User.objects.all()[0].name
-----------------------
from django.db import close_old_connections
try:
#do your long running operation here
except django.db.utils.OperationalError:
close_old_connections()
#do your long running operation here
from channels.db import database_sync_to_async
async def connect(self):
self.username = await database_sync_to_async(self.get_name)()
def get_name(self):
return User.objects.all()[0].name
@database_sync_to_async
def get_name(self):
return User.objects.all()[0].name
-----------------------
from django.db import close_old_connections
try:
#do your long running operation here
except django.db.utils.OperationalError:
close_old_connections()
#do your long running operation here
from channels.db import database_sync_to_async
async def connect(self):
self.username = await database_sync_to_async(self.get_name)()
def get_name(self):
return User.objects.all()[0].name
@database_sync_to_async
def get_name(self):
return User.objects.all()[0].name
-----------------------
from django.db import close_old_connections
close_old_connections()
# do some db actions, it will reconnect db
-----------------------
[mysqld]
...
max_allowed_packet=128M
innodb_log_file_size = 128M # Fix kopano-server: SQL [00000088] info: MySQL server has gone away. Reconnecting, see https://jira.kopano.io/browse/KC-1053
[mysqld]
...
wait_timeout = 288000 # Increase timeout to 80h before Mysql server will also go away
-----------------------
[mysqld]
...
max_allowed_packet=128M
innodb_log_file_size = 128M # Fix kopano-server: SQL [00000088] info: MySQL server has gone away. Reconnecting, see https://jira.kopano.io/browse/KC-1053
[mysqld]
...
wait_timeout = 288000 # Increase timeout to 80h before Mysql server will also go away
-----------------------
def check_db(context):
# Do the code for running "SELECT 1" in the DB
return
updater.job_queue.run_repeating(check_db, interval=21600, first=21600)
from django.db import connection
connection.close_if_unusable_or_obsolete()
-----------------------
def check_db(context):
# Do the code for running "SELECT 1" in the DB
return
updater.job_queue.run_repeating(check_db, interval=21600, first=21600)
from django.db import connection
connection.close_if_unusable_or_obsolete()
Telegram bot ConversationHandler ignores fallbacks
MessageHandler(
Filters.text & (~ Filters.command),
first_handler,
)
how to get username of author using telegram bot?
from telegram import *
from telegram.ext import *
from dotenv import load_dotenv
from responses import *
load_dotenv()
def main():
updater=Updater(os.getenv("BOT_TOKEN"), use_context=True)
dp=updater.dispatcher
dp.add_handler(MessageHandler(Filters.regex('^(hello|hi)$'), hello))
dp.add_handler(MessageHandler(Filters.regex('^(who are you)$'), whoareyou))
dp.add_error_handler(error)
updater.start_polling()
updater.idle()
main()
def hello(update: Update, context: CallbackContext) -> None:
try:
username = update.message.chat.username
except:
username = update.message.chat.first_name
update.message.reply_text(f'Hey! @{username} How it going?')
def whoareyou(update: Update, context: CallbackContext) -> None:
update.message.reply_text('Hi! I am Buddy Bot. Developed by Soham.')
-----------------------
from telegram import *
from telegram.ext import *
from dotenv import load_dotenv
from responses import *
load_dotenv()
def main():
updater=Updater(os.getenv("BOT_TOKEN"), use_context=True)
dp=updater.dispatcher
dp.add_handler(MessageHandler(Filters.regex('^(hello|hi)$'), hello))
dp.add_handler(MessageHandler(Filters.regex('^(who are you)$'), whoareyou))
dp.add_error_handler(error)
updater.start_polling()
updater.idle()
main()
def hello(update: Update, context: CallbackContext) -> None:
try:
username = update.message.chat.username
except:
username = update.message.chat.first_name
update.message.reply_text(f'Hey! @{username} How it going?')
def whoareyou(update: Update, context: CallbackContext) -> None:
update.message.reply_text('Hi! I am Buddy Bot. Developed by Soham.')
QUESTION
How to use Google Oauth2.0 to authenticate user via Telegram Bot
Asked 2022-Mar-30 at 08:56This is my first time interacting with Google API and I'm using python3.9 with this library Python Telegram Bot I want to access a user Google API Calendar via a telegram bot and I can't seem to find any article to guide me through it. My key problem (I think) is redirecting the success authorization flow back to telegram bot.
This is what I have in mind:
The problem lies betweeen step 3 and 4. A standard authorization link is
https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=<clientid>&redirect_uri=<redirect_uri>&scope=<scope>&state<state>&access_type=offline
How do I send the authorization link back to my telegram bot? Should I create another API endpoint to receive that authorization link? Or can I send telegram api send_message() in the <redirect_uri> to redirect the success message to my bot.
Update 1
Thanks to CallMeStag, I manage to figure out a way to complete the oauth process. For people who faced the same problem, this is what I did Pre-requisite: Credentials is created in google console api - Web application. redirect_uri set as localhost:8000 (During development phase)
https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=<clientid>&redirect_uri=
http://localhost:8000/
&scope=<scope>&state<state>&access_type=offline
http://localhost:8000
. Used fastapi as a webhook to receive the message. Capture the authorization code, use google.oauthlib.flow
to complete the authorization process. Next, redirect user back to telegram link https://t.me/<botname>
ANSWER
Answered 2022-Mar-29 at 06:44It's currently indeed not very straight forward for a PTB-application to listen for external updates (the auth verification in this cas) - see also this issue. Currently it might be easiest for you to set up a custom webhook application that runs in parallel to the Updater
- e.g. using flask/django/starlette/fastapi/…. Alternatively, if you're using webhooks for your bot anyway, you can patch the Updater
to do the job for you. Although that requires some manual work - see here for an example.
Once you are able to listen to updates coming from Google, handling them can be done via PTBs usual handler setup, specifically via the TypeHandler
or even a custom Handler
subclass - see this FAQ entry.
Regarding the redirect url: You'll want to redirect your user back to your bot, so you'll have to provide a link that does that. Bot.link
should probably do the trick.
Disclaimer: I'm currently the maintainer of python-telegram-bot
.
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
No vulnerabilities reported
Save this library and start creating your kit
Save this library and start creating your kit