Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Frequently Asked Questions

Aditya Yadav edited this pageFeb 17, 2024 ·81 revisions

Frequently Asked Questions

Note: You may also want to check the officialTelegram Bot FAQ.

What messages can my Bot see?

From the officialTelegram Bot FAQ:

All bots, regardless of settings, will receive:

  • All service messages.
  • All messages from private chats with users.
  • All messages from channels where they are a member.

Bot admins and bots with privacy mode disabled will receive all messages except messages sent by other bots.

Bots with privacy mode enabled will receive:

  • Commands explicitly meant for them (e.g., /command@this_bot).
  • General commands from users (e.g. /start) if the bot was the last bot to send a message to the group.
  • Messages sent via this bot.
  • Replies to any messages implicitly or explicitly meant for this bot.

Note that each particular message can only be available to one privacy-enabled bot at a time, i.e., a reply to bot A containing an explicit command for bot B or sent via bot C will only be available to bot A. Replies have the highest priority.

⚠️🚨Note: 🚨⚠️

Turning off the privacy mode has no effect for groups the bot is already in (because obviously that would be a security issue). You need to re-add your bot to those groups.

What about messages from other Bots?

From the officialTelegram Bot FAQ:

Bots talking to each other could potentially get stuck in unwelcome loops. To avoid this, we decided that bots will not be able to see messages from other bots regardless of mode.

Although, It is still possible to see a bot message if bot is replied to, withreply_to_message but you can't do any actions(forward etc) except delete on this message.

Can my bot delete messages from the user in a private chat?

Yes, but only within the first 48 hours.

How can I get a list of all chats/users/channels my bot is interacting with?

There is no method for that. You'll need to keep track. See e.g. thechatmemberbot.py example.

Does my bot get an update, when someone joins my channel?

Yes. We receive ChatMemberUpdated update.

My bot doesn't receive messages from groups. Why?

Seehere. TL;DR: Disable group privacy with@BotFather⚠️🚨and re-add your bot to the group 🚨⚠️

Can you add [feature] to PTB? Can I do [thing] with my bot?

Please note that python-telegram-bot is only awrapper for the Telegram Bot API, i.e. PTB can only provide methods that are available through the API.You can find a full list of all available methods in theofficial docs.Anythingnot listed there can not be done with bots. Here is a short list of frequently requested tasks, that cannot be done with the Bot API:

  • Getting a list of all members of a group. You'll need to keep track, e.g. using approaches displayed inchatmemberbot.py
  • Adding members to a group/channel (note that you can just send an invite link, which is also less likely to be seen as spam)
  • Clearing the chat history for a user
  • Getting a message by itsmessage_id (For the interested reader: seehere)
  • Getting the last sent message in a chat (you can keep track of that by usingchat_data)
  • Getting a usersuser_id via their@username (only userbots can do that - you may be interested inptbcontrib/username_to_chat_api)

In some cases, using a userbot can help overcome restrictions of the Bot API. Please have a look at thisarticle about userbots.Note that userbots arenot what python-telegram-bot is for.

Please also note that some methods marked in the Telegram API (aka MTProto) are marked as "usable for bots". This doesnot necessarily mean that they can be used directly via the Bot API.Seethis GitHub thread andthis discussion for more info on that.

I'm usingConversationHandler and want one handler to be run multiple times. How do I do that?

If your handlers callback returnsNone instead of the next state, you will stay in the current state. That means the next incoming update can be handled by the same callback.

I want to handle updates from an external service in addition to the Telegram updates. How do I do that?

Receiving updates from an external service, e.g. updates about your GitHub repo, is a common use case.Once you have such an update, you can put them in your bots update queue viaawait application.update_queue.put(your_update). Theupdate_queue is also available ascontext.update_queue.Note thatyour_update shouldnot need to be an instance oftelegram.Update, as it does not represent an update sent by Telegram. On the contrary,your_update can be any type of a Python object. You can e.g. write your own custom class to represent an update from your external service.To actually do something with the update, you can register aTypeHandler.StringCommandHandler andStringRegexHandler might also be interesting for some use cases.

But how to get the updates into your bot process?For many cases a simple approach is to check for updates every x seconds. You can use theJobQueue for that.If you can get the updates via a webhook, you can implement a custom webhook that handles both the Telegram and your custom updates. Please have a look atcustomwebhookbot.py example that showcases how that can be done.If your third-party service requires some other setup for fetching updates, that surely also be combined with PTB. Keep in mind that you basically only need access to the(application/context).update_queue.

Why am I gettingImportError: cannot import name 'XY' from 'telegram'?

There are three common reasons for this kind of exception:

  1. You installedpip install telegram instead ofpip install python-telegram-bot. Runpip uninstall telegram to uninstall thetelegram library and then runpip install python-telegram-bot again.
  2. You have a file namedtelegram.py or a directory/module namedtelegram in your working directory. This leads to namespace issues.Rename them to something else.
  3. You have misconfigured your python path/environment. Please check that the location listed inpip show python-telegram-bot is in yourPYTHONPATH, or yoursys.path. If not, then you may for e.g. append it toPYTHONPATH withexport PYTHONPATH=$PYTHONPATH:/path/to/python-telegram-bot, or append it tosys.path withsys.path.append('/path/to/python-telegram-bot').

What do theper_* settings inConversationHandler do?

ConversationHandler needs to decide somehow to which conversation an update belongs.The default setting (per_user=True andper_chat=True) means that in each chat each user can have its own conversation - even in groups.If you setper_user=False and you start a conversation in a group chat, theConversationHandler will also accept input from other users.Conversely, ifper_user=True, butper_chat=False, its possible to start a conversation in one chat and continue with it in another.

per_message is slightly more complicated: Imagine two different conversations, in each of which the user is presented with an inline keyboard with the buttons yes and no.The user now startsboth conversations and seestwo such keyboards. Now, which conversation should handle the update?In order to clear this issue up, if you setper_message=True, theConversationHandler will use themessage_id of the message with the keyboard.Note that this approach can only work, if all the handlers in the conversation areCallbackQueryHandlers. This is useful for building interactive menus.

Note: If you have aCallbackQueryHandler in yourConversationHandler, you will see a warningIf 'per_message=True/False', …. It is awarning, not an error. If you're sure that you setper_message to the correct value, you can just ignore it.If you like it better, you can even mute with something like

fromwarningsimportfilterwarningsfromtelegram.warningsimportPTBUserWarningfilterwarnings(action="ignore",message=r".*CallbackQueryHandler",category=PTBUserWarning)

Seethis page for more info.

Can I check, if aConversationHandler is currently active for a user?

There is no built-in way to do that. You can however easily set a flag as e.g.context.user_data['in_conversation'] = True in yourentry_pointss and set it toFalse before returningConversationHandler.END.

How can I list all messages of a particular chat or search through them based on a search query?

There is no API method for that (seehere). If you really need this functionality, you'll need to save all the messages send to the chat manually. Keep in mind that

  1. In group chats your bot doesn't receive all messages, if privacy mode is enabled (seehere)
  2. Messages may be edited (in which case your bot will receive a corresponding update)
  3. Messages may be deleted (and there are no updates for "message deleted"!)

Why am I getting an errorThe following arguments have not been supplied?

Thecallback method you pass toJobQueue.run_* takes exactlyone argument, which is of typeCallbackContext. This is, because jobs are triggered by a schedule and not by an update from Telegram. If you want to access data in the callback that changes at runtime (e.g. because you schedule jobs on demand), you can:

  1. Accesscontext.bot_data.
  2. Pass{user, chat}_id to any of therun_*(...) methods so you can access them in yourcallback ascontext.{user, chat}_data
  3. Userun_*(…, data=additional_data). It can then be accessed within thecallback ascontext.job.data.

Note thatcontext.{user, chat}_data will beNone, if you don't pass the arguments{user, chat}_id to any of therun_*(...) methods.

How can I check the version of PTB I am using?

There are three easy ways to do this. Two work from the command line:pip show python-telegram-bot orpython -m telegram. One you run inside a python script (or the python console):import telegram, then callprint(telegram.__version__).

How do I access info about the message my bot sent?

All bot methods have a return value. For example to get themessage_id of a text message sent by your bot, you can do

message=awaitbot.send_message(…)message_id=message.message_id

Please check the docs for details about the return value of each bot method.

How can I print a table in a Telegram message? Is it a lost cause?

Long story short: yes, it's a lost cause.Telegram formatting doesn't support tables and even if you try to get everything aligned with whitespaces and tabs, there WILL be a client that has a different max-widths for the text bubbles or a different font/font size and everything will be messed up.If it's important to you to send a nicely formatted table, send a picture or a pdf.

Can anInlineKeyboardButton have both a URL andcallback-data?

No, exactlyone of the optional arguments ofInlineKeyboardButton must be set.The closest that you can get to having both a URL andcallback_data in the button is:

  1. have a custom server (e.g.my.tld) where you can create redirect-links on the fly - something similar to bitly or all the other link shortening services
  2. each time you want to have both a URL and acallback_data, create a new linkmy.tld/some_token
    1. Makemy.tld/some_token redirect to the actual URL
    2. Configure your server such that it sends a notification to your bot telling it that themy.tld/some_token was accessed
  3. Make your bot process that information similar to how you'd process aCallbackQuery. See alsothis FAQ entry

Why am I suddenly getting so many log entries fromhttpx?

Starting withv.0.24.1,httpx logs all async requests atINFO level, which may be annoying for you as a PTB user.

You can explicitly set logging level forhttpx toWARNING to get rid of these messages:

importlogginglogging.getLogger("httpx").setLevel(logging.WARNING)

How can my bot use premium features?

Currently, Bot API allows only limited premium features to be used by bots, particularly sending custom emojis.Custom emoji entities can only be used by bots that purchased additional usernames onFragment in any chat.Additionally, bots can send custom emojis in specific groups without buying additional usernames if that group has sufficient amount of boosts to allow non premium members to send custom emojis from the groups emoji pack. Seeformatting options to know how to send custom emojis if your bot fulfills the necessary conditions.

Wiki ofpython-telegram-bot © Copyright 2015-2025 – Licensed byCreative Commons

Must read

  1. Introduction to the API
  2. Tutorial: Your first bot
  3. FAQ
  4. How to ask good questions
  5. How to write an MWE

Concepts & Important Elements

  1. Architecture Overview
  2. Builder Pattern forApplication
  3. Types of Handlers
  4. Working with Files and Media
  5. Exceptions, Warnings and Logging
  6. Concurrency in PTB

Notable Features

  1. Advanced Filters
  2. Storing data
  3. Making your bot persistent
  4. Adding Defaults
  5. Job Queue
  6. Arbitrarycallback_data
  7. Avoiding flood limits
  8. Webhooks
  9. Bot API Forward Compatiblity

Code Resources

  1. Frequently requested design patterns
  2. Code snippets
  3. Performance Optimizations
  4. Telegram Passport
  5. Bots built with PTB
  6. Automated Bot Tests

Examples explained

  1. InlineKeyboard Example

Networking

  1. Working Behind a Proxy
  2. Handling network errors

Other resources

  1. Where to host Telegram Bots
  2. How to host your bot
  3. Local API Server
  4. Type Checking with PTB
  5. Press
  6. Notes on GAE
  7. Related Projects
  8. Emoji

Transition Guides

Administration

Clone this wiki locally

[8]ページ先頭

©2009-2025 Movatter.jp