Giter Site home page Giter Site logo

pytelegrambotapi's Introduction

PyPi Package Version Supported Python versions Documentation Status PyPi downloads PyPi status

pyTelegramBotAPI

A simple, but extensible Python implementation for the Telegram Bot API.

Both synchronous and asynchronous.

Supported Bot API version: 7.2!

Contents

Getting started

This API is tested with Python 3.8-3.12 and Pypy 3. There are two ways to install the library:

  • Installation using pip (a Python package manager):
$ pip install pyTelegramBotAPI
  • Installation from source (requires git):
$ pip install git+https://github.com/eternnoir/pyTelegramBotAPI.git

It is generally recommended to use the first option.

While the API is production-ready, it is still under development and it has regular updates, do not forget to update it regularly by calling

pip install pytelegrambotapi --upgrade

Writing your first bot

Prerequisites

It is presumed that you have obtained an API token with @BotFather. We will call this token TOKEN. Furthermore, you have basic knowledge of the Python programming language and more importantly the Telegram Bot API.

A simple echo bot

The TeleBot class (defined in _init_.py) encapsulates all API calls in a single class. It provides functions such as send_xyz (send_message, send_document etc.) and several ways to listen for incoming messages.

Create a file called echo_bot.py. Then, open the file and create an instance of the TeleBot class.

import telebot

bot = telebot.TeleBot("TOKEN", parse_mode=None) # You can set parse_mode by default. HTML or MARKDOWN

Note: Make sure to actually replace TOKEN with your own API token.

After that declaration, we need to register some so-called message handlers. Message handlers define filters which a message must pass. If a message passes the filter, the decorated function is called and the incoming message is passed as an argument.

Let's define a message handler which handles incoming /start and /help commands.

@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
	bot.reply_to(message, "Howdy, how are you doing?")

A function which is decorated by a message handler can have an arbitrary name, however, it must have only one parameter (the message).

Let's add another handler:

@bot.message_handler(func=lambda m: True)
def echo_all(message):
	bot.reply_to(message, message.text)

This one echoes all incoming text messages back to the sender. It uses a lambda function to test a message. If the lambda returns True, the message is handled by the decorated function. Since we want all messages to be handled by this function, we simply always return True.

Note: all handlers are tested in the order in which they were declared

We now have a basic bot which replies a static message to "/start" and "/help" commands and which echoes the rest of the sent messages. To start the bot, add the following to our source file:

bot.infinity_polling()

Alright, that's it! Our source file now looks like this:

import telebot

bot = telebot.TeleBot("YOUR_BOT_TOKEN")

@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
	bot.reply_to(message, "Howdy, how are you doing?")

@bot.message_handler(func=lambda message: True)
def echo_all(message):
	bot.reply_to(message, message.text)

bot.infinity_polling()

To start the bot, simply open up a terminal and enter python echo_bot.py to run the bot! Test it by sending commands ('/start' and '/help') and arbitrary text messages.

General API Documentation

Types

All types are defined in types.py. They are all completely in line with the Telegram API's definition of the types, except for the Message's from field, which is renamed to from_user (because from is a Python reserved token). Thus, attributes such as message_id can be accessed directly with message.message_id. Note that message.chat can be either an instance of User or GroupChat (see How can I distinguish a User and a GroupChat in message.chat?).

The Message object also has a content_typeattribute, which defines the type of the Message. content_type can be one of the following strings: text, audio, document, animation, game, photo, sticker, video, video_note, voice, location, contact, venue, dice, new_chat_members, left_chat_member, new_chat_title, new_chat_photo, delete_chat_photo, group_chat_created, supergroup_chat_created, channel_chat_created, migrate_to_chat_id, migrate_from_chat_id, pinned_message, invoice, successful_payment, connected_website, poll, passport_data, proximity_alert_triggered, video_chat_scheduled, video_chat_started, video_chat_ended, video_chat_participants_invited, web_app_data, message_auto_delete_timer_changed, forum_topic_created, forum_topic_closed, forum_topic_reopened, forum_topic_edited, general_forum_topic_hidden, general_forum_topic_unhidden, write_access_allowed, user_shared, chat_shared, story.

You can use some types in one function. Example:

content_types=["text", "sticker", "pinned_message", "photo", "audio"]

Methods

All API methods are located in the TeleBot class. They are renamed to follow common Python naming conventions. E.g. getMe is renamed to get_me and sendMessage to send_message.

General use of the API

Outlined below are some general use cases of the API.

Message handlers

A message handler is a function that is decorated with the message_handler decorator of a TeleBot instance. Message handlers consist of one or multiple filters. Each filter must return True for a certain message in order for a message handler to become eligible to handle that message. A message handler is declared in the following way (provided bot is an instance of TeleBot):

@bot.message_handler(filters)
def function_name(message):
	bot.reply_to(message, "This is a message handler")

function_name is not bound to any restrictions. Any function name is permitted with message handlers. The function must accept at most one argument, which will be the message that the function must handle. filters is a list of keyword arguments. A filter is declared in the following manner: name=argument. One handler may have multiple filters. TeleBot supports the following filters:

name argument(s) Condition
content_types list of strings (default ['text']) True if message.content_type is in the list of strings.
regexp a regular expression as a string True if re.search(regexp_arg) returns True and message.content_type == 'text' (See Python Regular Expressions)
commands list of strings True if message.content_type == 'text' and message.text starts with a command that is in the list of strings.
chat_types list of chat types True if message.chat.type in your filter
func a function (lambda or function reference) True if the lambda or function reference returns True

Here are some examples of using the filters and message handlers:

import telebot
bot = telebot.TeleBot("TOKEN")

# Handles all text messages that contains the commands '/start' or '/help'.
@bot.message_handler(commands=['start', 'help'])
def handle_start_help(message):
	pass

# Handles all sent documents and audio files
@bot.message_handler(content_types=['document', 'audio'])
def handle_docs_audio(message):
	pass

# Handles all text messages that match the regular expression
@bot.message_handler(regexp="SOME_REGEXP")
def handle_message(message):
	pass

# Handles all messages for which the lambda returns True
@bot.message_handler(func=lambda message: message.document.mime_type == 'text/plain', content_types=['document'])
def handle_text_doc(message):
	pass

# Which could also be defined as:
def test_message(message):
	return message.document.mime_type == 'text/plain'

@bot.message_handler(func=test_message, content_types=['document'])
def handle_text_doc(message):
	pass

# Handlers can be stacked to create a function which will be called if either message_handler is eligible
# This handler will be called if the message starts with '/hello' OR is some emoji
@bot.message_handler(commands=['hello'])
@bot.message_handler(func=lambda msg: msg.text.encode("utf-8") == SOME_FANCY_EMOJI)
def send_something(message):
    pass

Important: all handlers are tested in the order in which they were declared

Edited Message handler

Handle edited messages @bot.edited_message_handler(filters) # <- passes a Message type object to your function

Channel Post handler

Handle channel post messages @bot.channel_post_handler(filters) # <- passes a Message type object to your function

Edited Channel Post handler

Handle edited channel post messages @bot.edited_channel_post_handler(filters) # <- passes a Message type object to your function

Callback Query Handler

Handle callback queries

@bot.callback_query_handler(func=lambda call: True)
def test_callback(call): # <- passes a CallbackQuery type object to your function
    logger.info(call)

Shipping Query Handler

Handle shipping queries @bot.shipping_query_handler() # <- passes a ShippingQuery type object to your function

Pre Checkout Query Handler

Handle pre checkoupt queries @bot.pre_checkout_query_handler() # <- passes a PreCheckoutQuery type object to your function

Poll Handler

Handle poll updates @bot.poll_handler() # <- passes a Poll type object to your function

Poll Answer Handler

Handle poll answers @bot.poll_answer_handler() # <- passes a PollAnswer type object to your function

My Chat Member Handler

Handle updates of a the bot's member status in a chat @bot.my_chat_member_handler() # <- passes a ChatMemberUpdated type object to your function

Chat Member Handler

Handle updates of a chat member's status in a chat @bot.chat_member_handler() # <- passes a ChatMemberUpdated type object to your function Note: "chat_member" updates are not requested by default. If you want to allow all update types, set allowed_updates in bot.polling() / bot.infinity_polling() to util.update_types

Chat Join Request Handler

Handle chat join requests using: @bot.chat_join_request_handler() # <- passes ChatInviteLink type object to your function

Inline Mode

More information about Inline mode.

Inline handler

Now, you can use inline_handler to get inline queries in telebot.

@bot.inline_handler(lambda query: query.query == 'text')
def query_text(inline_query):
    # Query message is text

Chosen Inline handler

Use chosen_inline_handler to get chosen_inline_result in telebot. Don't forgot add the /setinlinefeedback command for @Botfather.

More information : collecting-feedback

@bot.chosen_inline_handler(func=lambda chosen_inline_result: True)
def test_chosen(chosen_inline_result):
    # Process all chosen_inline_result.

Answer Inline Query

@bot.inline_handler(lambda query: query.query == 'text')
def query_text(inline_query):
    try:
        r = types.InlineQueryResultArticle('1', 'Result', types.InputTextMessageContent('Result message.'))
        r2 = types.InlineQueryResultArticle('2', 'Result2', types.InputTextMessageContent('Result message2.'))
        bot.answer_inline_query(inline_query.id, [r, r2])
    except Exception as e:
        print(e)

Additional API features

Middleware Handlers

A middleware handler is a function that allows you to modify requests or the bot context as they pass through the Telegram to the bot. You can imagine middleware as a chain of logic connection handled before any other handlers are executed. Middleware processing is disabled by default, enable it by setting apihelper.ENABLE_MIDDLEWARE = True.

apihelper.ENABLE_MIDDLEWARE = True

@bot.middleware_handler(update_types=['message'])
def modify_message(bot_instance, message):
    # modifying the message before it reaches any other handler 
    message.another_text = message.text + ':changed'

@bot.message_handler(commands=['start'])
def start(message):
    # the message is already modified when it reaches message handler
    assert message.another_text == message.text + ':changed'

There are other examples using middleware handler in the examples/middleware directory.

Class-based middlewares

There are class-based middlewares. Basic class-based middleware looks like this:

class Middleware(BaseMiddleware):
    def __init__(self):
        self.update_types = ['message']
    def pre_process(self, message, data):
        data['foo'] = 'Hello' # just for example
        # we edited the data. now, this data is passed to handler.
        # return SkipHandler() -> this will skip handler
        # return CancelUpdate() -> this will cancel update
    def post_process(self, message, data, exception=None):
        print(data['foo'])
        if exception: # check for exception
            print(exception)

Class-based middleware should have two functions: post and pre process. So, as you can see, class-based middlewares work before and after handler execution. For more, check out in examples

Custom filters

Also, you can use built-in custom filters. Or, you can create your own filter.

Example of custom filter

Also, we have examples on them. Check this links:

You can check some built-in filters in source code

Example of filtering by id

Example of filtering by text

If you want to add some built-in filter, you are welcome to add it in custom_filters.py file.

Here is example of creating filter-class:

class IsAdmin(telebot.custom_filters.SimpleCustomFilter):
    # Class will check whether the user is admin or creator in group or not
    key='is_chat_admin'
    @staticmethod
    def check(message: telebot.types.Message):
        return bot.get_chat_member(message.chat.id,message.from_user.id).status in ['administrator','creator']
	
# To register filter, you need to use method add_custom_filter.
bot.add_custom_filter(IsAdmin())
	
# Now, you can use it in handler.
@bot.message_handler(is_chat_admin=True)
def admin_of_group(message):
	bot.send_message(message.chat.id, 'You are admin of this group!')

TeleBot

import telebot

TOKEN = '<token_string>'
tb = telebot.TeleBot(TOKEN)	#create a new Telegram Bot object

# Upon calling this function, TeleBot starts polling the Telegram servers for new messages.
# - interval: int (default 0) - The interval between polling requests
# - timeout: integer (default 20) - Timeout in seconds for long polling.
# - allowed_updates: List of Strings (default None) - List of update types to request 
tb.infinity_polling(interval=0, timeout=20)

# getMe
user = tb.get_me()

# setWebhook
tb.set_webhook(url="http://example.com", certificate=open('mycert.pem'))
# unset webhook
tb.remove_webhook()

# getUpdates
updates = tb.get_updates()
# or
updates = tb.get_updates(1234,100,20) #get_Updates(offset, limit, timeout):

# sendMessage
tb.send_message(chat_id, text)

# editMessageText
tb.edit_message_text(new_text, chat_id, message_id)

# forwardMessage
tb.forward_message(to_chat_id, from_chat_id, message_id)

# All send_xyz functions which can take a file as an argument, can also take a file_id instead of a file.
# sendPhoto
photo = open('/tmp/photo.png', 'rb')
tb.send_photo(chat_id, photo)
tb.send_photo(chat_id, "FILEID")

# sendAudio
audio = open('/tmp/audio.mp3', 'rb')
tb.send_audio(chat_id, audio)
tb.send_audio(chat_id, "FILEID")

## sendAudio with duration, performer and title.
tb.send_audio(CHAT_ID, file_data, 1, 'eternnoir', 'pyTelegram')

# sendVoice
voice = open('/tmp/voice.ogg', 'rb')
tb.send_voice(chat_id, voice)
tb.send_voice(chat_id, "FILEID")

# sendDocument
doc = open('/tmp/file.txt', 'rb')
tb.send_document(chat_id, doc)
tb.send_document(chat_id, "FILEID")

# sendSticker
sti = open('/tmp/sti.webp', 'rb')
tb.send_sticker(chat_id, sti)
tb.send_sticker(chat_id, "FILEID")

# sendVideo
video = open('/tmp/video.mp4', 'rb')
tb.send_video(chat_id, video)
tb.send_video(chat_id, "FILEID")

# sendVideoNote
videonote = open('/tmp/videonote.mp4', 'rb')
tb.send_video_note(chat_id, videonote)
tb.send_video_note(chat_id, "FILEID")

# sendLocation
tb.send_location(chat_id, lat, lon)

# sendChatAction
# action_string can be one of the following strings: 'typing', 'upload_photo', 'record_video', 'upload_video',
# 'record_audio', 'upload_audio', 'upload_document' or 'find_location'.
tb.send_chat_action(chat_id, action_string)

# getFile
# Downloading a file is straightforward
# Returns a File object
import requests
file_info = tb.get_file(file_id)

file = requests.get('https://api.telegram.org/file/bot{0}/{1}'.format(API_TOKEN, file_info.file_path))

Reply markup

All send_xyz functions of TeleBot take an optional reply_markup argument. This argument must be an instance of ReplyKeyboardMarkup, ReplyKeyboardRemove or ForceReply, which are defined in types.py.

from telebot import types

# Using the ReplyKeyboardMarkup class
# It's constructor can take the following optional arguments:
# - resize_keyboard: True/False (default False)
# - one_time_keyboard: True/False (default False)
# - selective: True/False (default False)
# - row_width: integer (default 3)
# row_width is used in combination with the add() function.
# It defines how many buttons are fit on each row before continuing on the next row.
markup = types.ReplyKeyboardMarkup(row_width=2)
itembtn1 = types.KeyboardButton('a')
itembtn2 = types.KeyboardButton('v')
itembtn3 = types.KeyboardButton('d')
markup.add(itembtn1, itembtn2, itembtn3)
tb.send_message(chat_id, "Choose one letter:", reply_markup=markup)

# or add KeyboardButton one row at a time:
markup = types.ReplyKeyboardMarkup()
itembtna = types.KeyboardButton('a')
itembtnv = types.KeyboardButton('v')
itembtnc = types.KeyboardButton('c')
itembtnd = types.KeyboardButton('d')
itembtne = types.KeyboardButton('e')
markup.row(itembtna, itembtnv)
markup.row(itembtnc, itembtnd, itembtne)
tb.send_message(chat_id, "Choose one letter:", reply_markup=markup)

The last example yields this result:

ReplyKeyboardMarkup

# ReplyKeyboardRemove: hides a previously sent ReplyKeyboardMarkup
# Takes an optional selective argument (True/False, default False)
markup = types.ReplyKeyboardRemove(selective=False)
tb.send_message(chat_id, message, reply_markup=markup)
# ForceReply: forces a user to reply to a message
# Takes an optional selective argument (True/False, default False)
markup = types.ForceReply(selective=False)
tb.send_message(chat_id, "Send me another word:", reply_markup=markup)

ForceReply:

ForceReply

Working with entities

This object represents one special entity in a text message. For example, hashtags, usernames, URLs, etc. Attributes:

  • type
  • url
  • offset
  • length
  • user

Here's an Example:message.entities[num].<attribute>
Here num is the entity number or order of entity in a reply, for if incase there are multiple entities in the reply/message.
message.entities returns a list of entities object.
message.entities[0].type would give the type of the first entity
Refer Bot Api for extra details

Advanced use of the API

Using local Bot API Sever

Since version 5.0 of the Bot API, you have the possibility to run your own Local Bot API Server. pyTelegramBotAPI also supports this feature.

from telebot import apihelper

apihelper.API_URL = "http://localhost:4200/bot{0}/{1}"

Important: Like described here, you have to log out your bot from the Telegram server before switching to your local API server. in pyTelegramBotAPI use bot.log_out()

Note: 4200 is an example port

Asynchronous TeleBot

New: There is an asynchronous implementation of telebot. To enable this behaviour, create an instance of AsyncTeleBot instead of TeleBot.

tb = telebot.AsyncTeleBot("TOKEN")

Now, every function that calls the Telegram API is executed in a separate asynchronous task. Using AsyncTeleBot allows you to do the following:

import telebot

tb = telebot.AsyncTeleBot("TOKEN")

@tb.message_handler(commands=['start'])
async def start_message(message):
	await bot.send_message(message.chat.id, 'Hello!')

See more in examples

Sending large text messages

Sometimes you must send messages that exceed 5000 characters. The Telegram API can not handle that many characters in one request, so we need to split the message in multiples. Here is how to do that using the API:

from telebot import util
large_text = open("large_text.txt", "rb").read()

# Split the text each 3000 characters.
# split_string returns a list with the splitted text.
splitted_text = util.split_string(large_text, 3000)

for text in splitted_text:
	tb.send_message(chat_id, text)

Or you can use the new smart_split function to get more meaningful substrings:

from telebot import util
large_text = open("large_text.txt", "rb").read()
# Splits one string into multiple strings, with a maximum amount of `chars_per_string` (max. 4096)
# Splits by last '\n', '. ' or ' ' in exactly this priority.
# smart_split returns a list with the splitted text.
splitted_text = util.smart_split(large_text, chars_per_string=3000)
for text in splitted_text:
	tb.send_message(chat_id, text)

Controlling the amount of Threads used by TeleBot

The TeleBot constructor takes the following optional arguments:

  • threaded: True/False (default True). A flag to indicate whether TeleBot should execute message handlers on it's polling Thread.

The listener mechanism

As an alternative to the message handlers, one can also register a function as a listener to TeleBot.

NOTICE: handlers won't disappear! Your message will be processed both by handlers and listeners. Also, it's impossible to predict which will work at first because of threading. If you use threaded=False, custom listeners will work earlier, after them handlers will be called. Example:

def handle_messages(messages):
	for message in messages:
		# Do something with the message
		bot.reply_to(message, 'Hi')

bot.set_update_listener(handle_messages)
bot.infinity_polling()

Using web hooks

When using webhooks telegram sends one Update per call, for processing it you should call process_new_messages([update.message]) when you recieve it.

There are some examples using webhooks in the examples/webhook_examples directory.

Logging

You can use the Telebot module logger to log debug info about Telebot. Use telebot.logger to get the logger of the TeleBot module. It is possible to add custom logging Handlers to the logger. Refer to the Python logging module page for more info.

import logging

logger = telebot.logger
telebot.logger.setLevel(logging.DEBUG) # Outputs debug messages to console.

Proxy

For sync:

You can use proxy for request. apihelper.proxy object will use by call requests proxies argument.

from telebot import apihelper

apihelper.proxy = {'http':'http://127.0.0.1:3128'}

If you want to use socket5 proxy you need install dependency pip install requests[socks] and make sure, that you have the latest version of gunicorn, PySocks, pyTelegramBotAPI, requests and urllib3.

apihelper.proxy = {'https':'socks5://userproxy:password@proxy_address:port'}

For async:

from telebot import asyncio_helper

asyncio_helper.proxy = 'http://127.0.0.1:3128' #url

Testing

You can disable or change the interaction with real Telegram server by using

apihelper.CUSTOM_REQUEST_SENDER = your_handler

parameter. You can pass there your own function that will be called instead of requests.request.

For example:

def custom_sender(method, url, **kwargs):
    print("custom_sender. method: {}, url: {}, params: {}".format(method, url, kwargs.get("params")))
    result = util.CustomRequestResponse('{"ok":true,"result":{"message_id": 1, "date": 1, "chat": {"id": 1, "type": "private"}}}')
    return result

Then you can use API and proceed requests in your handler code.

apihelper.CUSTOM_REQUEST_SENDER = custom_sender
tb = TeleBot("test")
res = tb.send_message(123, "Test")

Result will be:

custom_sender. method: post, url: https://api.telegram.org/botololo/sendMessage, params: {'chat_id': '123', 'text': 'Test'}

API conformance limitations

AsyncTeleBot

Asynchronous version of telebot

We have a fully asynchronous version of TeleBot. This class is not controlled by threads. Asyncio tasks are created to execute all the stuff.

EchoBot

Echo Bot example on AsyncTeleBot:

# This is a simple echo bot using the decorator mechanism.
# It echoes any incoming text messages.

from telebot.async_telebot import AsyncTeleBot
import asyncio
bot = AsyncTeleBot('TOKEN')



# Handle '/start' and '/help'
@bot.message_handler(commands=['help', 'start'])
async def send_welcome(message):
    await bot.reply_to(message, """\
Hi there, I am EchoBot.
I am here to echo your kind words back to you. Just say anything nice and I'll say the exact same thing to you!\
""")


# Handle all other messages with content_type 'text' (content_types defaults to ['text'])
@bot.message_handler(func=lambda message: True)
async def echo_message(message):
    await bot.reply_to(message, message.text)


asyncio.run(bot.polling())

As you can see here, keywords are await and async.

Why should I use async?

Asynchronous tasks depend on processor performance. Many asynchronous tasks can run parallelly, while thread tasks will block each other.

Differences in AsyncTeleBot

AsyncTeleBot is asynchronous. It uses aiohttp instead of requests module.

Examples

See more examples in our examples folder

F.A.Q.

How can I distinguish a User and a GroupChat in message.chat?

Telegram Bot API support new type Chat for message.chat.

  • Check the type attribute in Chat object:
if message.chat.type == "private":
    # private chat message

if message.chat.type == "group":
	# group chat message

if message.chat.type == "supergroup":
	# supergroup chat message

if message.chat.type == "channel":
	# channel message

How can I handle reocurring ConnectionResetErrors?

Bot instances that were idle for a long time might be rejected by the server when sending a message due to a timeout of the last used session. Add apihelper.SESSION_TIME_TO_LIVE = 5 * 60 to your initialisation to force recreation after 5 minutes without any activity.

The Telegram Chat Group

Get help. Discuss. Chat.

Telegram Channel

Join the News channel. Here we will post releases and updates.

More examples

Code Template

Template is a ready folder that contains architecture of basic project. Here are some examples of template:

Bots using this library

Want to have your bot listed here? Just make a pull request. Only bots with public source code are accepted.

pytelegrambotapi's People

Contributors

abdullaev388 avatar aragroth avatar areeg94fahad avatar artyl avatar badiboy avatar barbax7 avatar bedilbek avatar coder2020official avatar cub11k avatar dependabot[bot] avatar drforse avatar egorkhabarov avatar eternnoir avatar heyyyoyy avatar istoleabread avatar kylmakalle avatar mastergroosha avatar meoww-bot avatar modischfabrications avatar monsterdeveloper avatar mrsobakin avatar otxoto avatar p0lunin avatar pevdh avatar reddere avatar sviat9440 avatar swisscorepy avatar uburuntu avatar wafflelapkin avatar zeph1997 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pytelegrambotapi's Issues

Arguments for register_next_step_handler

Hello,

I want to be able to pass arguments to my callback function.

register_next_step_handler(message, callback, args*) ???

This would be very usefull, because a global dictionary with data is unnecessary then.

Thanks,
Matthias

Detailed Example Bot

Hey eternnoir,

I'm just getting started with this awesome API.

After some trouble, I got the listener and the custom keyboards working perfectly fine.
But now I'm wondering... If I register a handler on the command '/start'. Do I have to do additional filtering manually in the handler?

Because you have non-linked examples, it's quite hard to understand everything easily.
It would be REALLY helpful, if you could include an example in the Readme, that includes every feature of your really useful library in one example (listener on normal messages, custom keyboards, command handlers, chat actions and maybe even multimedia handling (sending/receiving).

Because I want to use all that in a project, but can't seem to get every component to work together...

Thank you very much in advance,
LeoDJ

Webhook with flask on google app engine, SSL error

I am using pyTelegramBotAPI and flask for handel my telegram bot messages. I'm using the new method process_new_messages. Every thing is all right but when i want to send a reply message in listener function, requests module raise an exception about SSL connection:

File "/base/data/home/apps/s~mynerdbot/1.385939809966824449/lib/requests/adapters.py", line 429, in send
    raise SSLError(e, request=request)
SSLError: Can't connect to HTTPS URL because the SSL module is not available.

I test urllib for sent message. It wat ok.
I test requests manually and result was SSLError.

Please, add KeyboardHide class

I've made ReplyKeyboardHide class, but it requires some changes in convert_markup() function, so, I'm leaving it to you:
Here's the necessary class:

class ReplyKeyboardHide:
    def __init__(self, hide_keyboard=None, selective=None):
        self.hide_keyboard = hide_keyboard
        self.selective = selective

    def to_json(self):
        json_dict = {}
        if self.hide_keyboard:
            json_dict['hide_keyboard'] = True
        if self.selective:
            json_dict['selective'] = True
        return json.dumps(json_dict)

Error sending big files

I'm trying to send big files (20MB is enough) and after some time sending the file, it reaches the point where this error is shown:

ConnectionError: HTTPSConnectionPool(host='api.telegram.org', port=443): Max retries exceeded with url: /botTOKEN/sendDocument?chat_id=8214509 (Caused by <class 'socket.error'>: [Errno 10054] An existing connection was forcibly closed by the remote host.)

Set user specified timeout for polling?

With bot.polling(), currently the bot polls as many times as it likes. Since I don't need an instant response it would be good to be able to optionally limit the loop to only cycle every x seconds (e.g. bot.polling(1)).

[Feature Request] Split large messages onto smaller before sending

Some bots are intended to send large piles of data (news articles, for example). When sending large texts, you may encounter HTTP Error 414 ("Request URI Too Long")

In this case, I've started using the following function (found on StackOverflow):

def string_splitter(line, chars_in_each_line):
    return [line[i:i + chars_in_each_line] for i in range(0, len(line), chars_in_each_line)]

It returns an array of chunks, chars_in_each_line long each.
I can't say which number is max supported, but 2000 seems fine.
So, maybe you could add a parameter to send_message? (f.ex. single_message_length)

Let client support next_step_handler to handle message which user replay.

We let bot handle command like '/search google'. It easy to implement by pyTelegramBotAPI.
But if we want split this command to '/search','google' two step. Not that simple now.

So I want to create new method like register_for_new_message. Use them like this:

def process_step1(message):
    if message.text == 'No':
        bot.reply_to(message, "Good bye!")
    else:
        sent_message = bot.send_message(chat_id, "Go to step2?", )
        bot.register_for_new_message(sent_message, process_step2)

def process_step2(message):
    if message.text == 'No':
        bot.reply_to(message, "Good bye!")
    else:
        sent_message = bot.send_message(chat_id, "Go to step3?", )
        bot.register_for_new_message(sent_message, process_step3)

def process_step3(message):
    bot.reply_to(message, "Well done.")

sent_message = bot.send_message(chat_id, "Go to step1?", )
bot.register_for_new_message(sent_message, process_step1)

CPU 100% after commit #e3025f4

On commit #e3025f4 is suggested the change:

while True:
    time.sleep(20)

to:

while True: # Don't let the main Thread end.
    pass

But i've noticed that using this last method makes CPU goes to 100% all the time. I believe the time.sleep() is better.

Exception in register_next_step_handler

In init.py, lines 368-370

chat_id = message.chat.id
if chat_id in self.message_subscribers_next_step:
    self.message_subscribers_next_step.append(callback)

Last string should be
self.message_subscribers_next_step[chat_id].append(callback)

How to disable using HTTPS?

Hello, how to disable InsecurePlatformWarnings?
I'm running bot on my ODroid with no private SSL keys.

I see "API_URL" string in __init__.py file. Changed https to http -> still have warnings. Do I have to rebuild this lib somehow? (installed via git clone and setup.py)

Response [502]

Hi, I made a script that should works forever (while True) but a few hours later getUpdates fails and return this:
image

Any ideas? Thank you

IOError: [Errno 2] No such file or directory: 'README.rst'

$ setup.py install

Traceback (most recent call last):
 File "setup.py", line 11, in <module>
 long_description=readme(),
 File "setup.py", line 5, in readme
 with open('README.rst') as f:
IOError: [Errno 2] No such file or directory: 'README.rst'

Custom Keyboard

Could you please provide example for custom keyboard layouts?
I'm making an array of buttons:

newsTitles = 10 * ['MyButton']
news_keyboard = {'keyboard': newsTitles, 'one_time_keyboard': 'true'}

and then try to send message:
tb.send_message(chatid, 'Choose news:', None, None, news_keyboard)

but no custom keyboards are seen

Bots are unable to download received files/photos/videos

When bots receive a file/photo/video/sticker, they are unable to download it from the Telegram servers.

As far as I know, this is a limitation of the Telegram Bot API. I really hope they add this feature anytime soon to their API.

Connection exceptions

The __polling() method takes into account API exceptions when polling for updates. While the none_stop argument prevents the thread from stopping in case these exceptions occur, it will stop if it encounters a connection exception (such as those from the requests module).

Would it be possible to also skip and/or log these exceptions when using the none_stop argument so that it is not necessary to manually restart the bot?

[Question] Can I mark message as viewed when I want?

Hi! I'm asking that If I can mark a message as viewed only when my bots finish their work.

For example, when bot fails because of an API update or simply my fault, these messages are lost. Is there any way to hold this messages until I manage them properly?

[ERROR] 'list' object has no attribute 'chat' error after upgrading 0.2.0 -> 0.2.2

Hello. After upgrading from 0.2.0 to 0.2.2 I'm facing the following error:

Traceback (most recent call last):
  File "/usr/lib/python3.4/threading.py", line 920, in _bootstrap_inner
    self.run()
  File "/usr/local/lib/python3.4/dist-packages/telebot/__init__.py", line 39, in run
    task(*args, **kwargs)
  File "./bashbot.py", line 13, in listener
    chatid = m.chat.id
AttributeError: 'list' object has no attribute 'chat'

piece of code, where error happens (error in 3rd line here):

def listener(*messages):
    for m in messages:
        chatid = m.chat.id
        if m.content_type == 'text' and m.text.startswith('/bash'):
            tb.send_message(chatid, bash.getQuote())
            parse_stats.update_analytics(chatid, 'bash')

The code in README (Echo bot) doesn't work any longer in 0.2.2, hovewer after reverting to 0.2.0 it works.
What's even worse, I can't find the commit which breaks it all...

Explicitly create Threads instead of implicitly?

Threading is a complicated subject and it can lead to difficult to track bugs.
By default TeleBot creates a new Thread for each registered listener and each registered message handler. Now, if two message handlers or two listeners try to access the same (not thread-safe) resource, the programmer has got a problem. So unless the programmer is aware that this library creates Threads (and knows how to handle them (locks, semaphores, queues)), Threads can be a threat ( :) ) to the stability of bots.
My proposal:
Create an optional create_threads parameter for the TeleBot constructor, which defaults to False.
Check for this parameter when calling listeners or message handlers:

if self.create_threads:
    t = threading.Thread(target=message_handler, args=message)
    t.start()
else:
    message_handler(message)

The drawback of this is of course program speed. The bot will block until a listener or message handler has returned. Until then the bot cannot receive new messages. But my estimation is that this drawback is less important than the overhead (for the, especially novice, programmer) of creating Threads. With an optional argument, the programmer can decide for himself whether he wants to go down the dangerous road of multithreading.
Is my reasoning correct?

one_time_keyboard not working (?)

Hello! I've tried both markup = types.ReplyKeyboardMarkup(one_time_keyboard=True) and

markup = types.ReplyKeyboardMarkup()
markup.one_time_keyboard=True

Custom keyboard stays visible forever. The only way now to hide it is to send another message with ReplyKeyboardHide

Unhandled exceptions in the polling Thread causes bot to stop working but the process doesn't die.

If an Exception occurs in the polling Thread, then the bot stays running but not receiving more updates, seems like the polling thread dies but doesn't exit the process.

More Info in #78 (comment)

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 763, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/home/sergio/.local/lib/python2.7/site-packages/telebot/__init__.py", line 145, in __polling
    self.get_update()
  File "/home/sergio/.local/lib/python2.7/site-packages/telebot/__init__.py", line 87, in get_update
    updates = self.get_updates(offset=(self.last_update_id + 1), timeout=3)
  File "/home/sergio/.local/lib/python2.7/site-packages/telebot/__init__.py", line 75, in get_updates
    json_updates = apihelper.get_updates(self.token, offset, limit, timeout)
  File "/home/sergio/.local/lib/python2.7/site-packages/telebot/apihelper.py", line 117, in get_updates
    return _make_request(token, method_url, params=payload)
  File "/home/sergio/.local/lib/python2.7/site-packages/telebot/apihelper.py", line 26, in _make_request
    result = requests.request(method, request_url, params=params, files=files)
  File "/usr/lib/python2.7/dist-packages/requests/api.py", line 49, in request
    return session.request(method=method, url=url, **kwargs)
  File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 457, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 569, in send
    r = adapter.send(request, **kwargs)
  File "/usr/lib/python2.7/dist-packages/requests/adapters.py", line 420, in send
    raise SSLError(e, request=request)
SSLError: EOF occurred in violation of protocol (_ssl.c:581)

Request for Secret Chat

Do you have any plan on adding secret chats support?
I had an idea that I would like to use it. Reading your API, the one I like the most, I could not find anything about it.
If possible, please add this functionality! :D

problem in register_next_step_handler function

if I have a code something like this:

@bot.message_handler(commands=['config'])
def set_config(message):
    bot.reply_to(message, 'enter password')
    bot.register_next_step_handler(message, check_password)

def check_password(message):
    if message.text == password:
        bot.reply_to(message, 'OK')
        bot.register_next_step_handler(message, next_step_func)
    else:
        bot.reply_to(message, 'Invalid password')
        bot.register_next_step_handler(message, check_password)

If a person send for my bot /config and when I ask them to type password maybe he/she send me /config again. so set_config() and check_password() called together.
how can I solve this problem? :)

getUpdates - update_id

I've noticed that my bot is freezing.
After some investigation, it seems that the offset is not increasing correctly.
If I access via browser https://api.telegram.org/botTOKEN/getUpdates?offset=update_id+1 the bot unfreezes and won't stop again until it reaches 100 updates.
It is also happening on commit 924099d.

Updating lib

Hello! I'm running Ubuntu 14.04 with pyTelegramBotAPI version about 0.1.5 or so
How can I update it?
I've pulled the newest code from this repo, ran sudo python2.7 setup.py install and tried to use new functions (f.ex. markup = types.ReplyKeyboardMarkup())
However, I get error 'module' object has no attribute 'ReplyKeyboardMarkup'

Improve de_json

opts['sticker'] = Sticker.de_json(json.dumps(obj['sticker']))

to create sticker object bu de_json function need json string. But it has better way to create object without json_dumps.

Send files via file_id fail (0.2.4)

file_id = 'My_ID_here'
tb.send_audio(m.chat.id, file_id)

fails with the following error (API v0.2.4)

    tb.send_audio(m.chat.id, file_id)
  File "/usr/local/lib/python3.4/dist-packages/telebot/__init__.py", line 231, in send_audio
    apihelper.send_data(self.token, chat_id, data, 'audio', reply_to_message_id, reply_markup))
  File "/usr/local/lib/python3.4/dist-packages/telebot/apihelper.py", line 124, in send_data
    if isinstance(data, file):
NameError: name 'file' is not defined

[Not a bug][Question] How to get file_id of sent file?

Hello! I'm doing my best to optimize bot's traffic and speed.
One of my bots downloads pictures and sends then to multiple recipients. For now, he [bot] sends them as file every time.

I wonder, if it's possible somehow to send file once, find out its file_id so that other people will get this image via file_id?

Add to doc

I think it's worth mentioning in the docs that the message_handler decorators can be stacked to produce an OR filter, i.e.:

@bot.message_handler(commands=[CMD])
@bot.message_handler(func=lambda msg: msg.text.encode("utf-8") == SOME_FANCY_EMOJI)
def send_something(message):
    pass

CPU overload after update

Hi! After last update (or an older one) I have my Raspberry Pi CPU overloaded. I saw the new block parameter and other things but I don't know my problem. What do I have missed?

webHooks using webapp2?

I am using pyTelegramBotAPI wrapper and I really like the way how it handles commands and messages through decorator mechanism. I like it so much so I don't want to switch to any other wrapper. However its infinite polling loop sometimes causing network related problems. I have made my own local customisations to retry the polling attempt in case of failure, but it would be awesome if we could extend this wrapper for webHooks as well. We could use webapp2 as a framework for endpoints.
In this way, instead of infinitely polling for updates, the web application would respond to callbacks immediately. Any ideas?

My bot is suddenly stoping

I'm getting this several times a day:

TeleBot: Exception occurred. Stopping.
getUpdates failed. Returned result: <Response [502]>
TeleBot: Stopped polling.

Knowing that 'The 502 Bad Gateway error is an HTTP status code that means that one server received an invalid response from another server', I believe it is an error on Telegram's server, not on the API.

So I would be happy if someone could give me an suggestion on how to treat this and make my bot automatically begin to work again.

Send file/sticker/audio by ID

Is there some way to send a file/sticker/etc by ID (already stored in Telegram's server) instead of upload the file again?

Message without username

First of all, thank you for the API! It's really useful!

I've noticed that the bot won't send messages (photos/files etc) to people that doesn't have an username.
As far as I read, it's a limitation from the Telegram API. Can you confirm that, please?

Make clients able to register for message replies

It would be useful to not only be able to subscribe to certain commands, but also subscribe to message replies.
For example:
Bot sends: "How many apples do you want?", person replies "3". How does the bot know that the person is replying to his question?
This can be solved by adding a register_for_reply function or something similar.

This is how that would look:

def process_reply(message):
    bot.reply_to(message, "Good choice!")

sent_message = bot.send_message(chat_id, "How many apples do you want?", reply_markup=types.ForceReply())
bot.register_for_reply_to(sent_message, process_reply)

register_for_reply_to would store the sent_message.message_id and process_reply in a dictionary.
When the bot receives a message with message.reply_to_message.message_id == sent_message.message_id he notifies process_reply and passes the message to the function.

I would have implemented this myself, but I will be away for the coming few weeks, so I thought I would just make an issue about this idea :) I hope you get the idea, if not, feel free to ask for clarification.

Full system load with these bots

Hello again.
In you README in "echo-bot" example you write:

while True: # Don't let the main Thread end.
    pass

previously there was time.sleep(20) string.
I've tried your new variant and I'm having 95-100% load on CPU (with pass only)
I've changed to

while True:
    time.sleep(20)

and now it's fine (1-3% load)

Could you please explain this? Is it API problem or anything else?

Can't kill the echo bot example

First, great work! It has been very useful and fun to me.
I copy/pasted the example, but can't be interrupted with the KeyboardInterrupt signal on Gentoo.
IMHO one possible fix could be change the main loop at the end:
try:
while 1:
time.sleep(20)
except KeyboardInterrupt:
tb.stop_polling()

When sending message to bot : AttributeError: 'list' object has no attribute 'chat'

Exception in thread WorkerThread1:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
    self.run()
  File "/home/n07070/.local/lib/python2.7/site-packages/telebot/__init__.py", line 39, in run
    task(*args, **kwargs)
  File "main.py", line 47, in echo_messages
    chatid = m.chat.id
AttributeError: 'list' object has no attribute 'chat'

409 Conflict

I've been getting 409 API Error 5 times today in line

Traceback (most recent call last):
  File "meduzabot.py", line 79, in <module>
    tb.get_update()  # cache exist message
  File "/usr/local/lib/python3.4/dist-packages/telebot/__init__.py", line 50, in get_update
    updates = apihelper.get_updates(self.token, offset=(self.last_update_id + 1), timeout=20)
  File "/usr/local/lib/python3.4/dist-packages/telebot/apihelper.py", line 68, in get_updates
    return _make_request(token, method_url, params=payload)
  File "/usr/local/lib/python3.4/dist-packages/telebot/apihelper.py", line 22, in _make_request
    raise ApiException(method_name, result)
telebot.apihelper.ApiException: getUpdates failed. Returned result: <Response [409]>

Is it something wrong with my code or these are Telegram servers' faults?

No handlers could be found for logger "Telebot"

Hi, sometimes after my script is running, I get this message in the console and the script stops so I have to finish it and run it again. Do you know what could be? I leave you the code, it's very simple.

import telebot
from telebot import types
import time
TOKEN = ''
def listener(messages):
"""
When new messages arrive TeleBot will call this function.
"""
for m in messages:
cid = m.chat.id
if m.content_type == 'text':
#print the sent message to the console
#print str(m.chat.first_name) + " [" + str(m.chat.id) + "]: " + m.text
print " [" + str(m.chat.id) + "]: " + m.text

bot = telebot.TeleBot(TOKEN)
bot.set_update_listener(listener) #register listener
try:
bot.polling()
except Exception:
pass

Funcion de repetir mensajes.

@bot.message_handler(commands=['repite'])
def echo_message(message):
repetir = message.text[7:]
bot.reply_to(message, repetir)
print "Edurolp_bot [" + str(message.chat.id) + "]: " + repetir

Funcion flood

@bot.message_handler(commands=['flood'])
def flood_command(message):
repetir = message.text[6:]
#print "Edurolp_bot [" + str(message.chat.id) + "]: " + repetir + "(x10)"
contador = 0
while contador < 10:
bot.send_message(message.chat.id , repetir)
contador = contador + 1
#print "Edurolp_bot [" + str(message.chat.id) + "]: " + repetir + "(x10)"

while True:
time.sleep(0)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.