Coder Social home page Coder Social logo

python-telegram-bot / python-telegram-bot Goto Github PK

View Code? Open in Web Editor NEW
24.8K 607.0 5.0K 13.78 MB

We have made you a wrapper you can't refuse

Home Page: https://python-telegram-bot.org

License: GNU General Public License v3.0

Python 99.99% Makefile 0.01% Shell 0.01%
python telegram bot chatbot framework hacktoberfest

python-telegram-bot's Introduction

python-telegram-bot Logo

PyPi Package Version

Supported Python versions

PyPi Package Monthly Download

Documentation Status

LGPLv3 License

Github Actions workflow

Code coverage

Median time to resolve an issue

Code quality: Codacy

pre-commit.ci status

Code Style: Black

Telegram Channel

Telegram Group

We have made you a wrapper you can't refuse

We have a vibrant community of developers helping each other in our Telegram group. Join us!

Stay tuned for library updates and new releases on our Telegram Channel.

Introduction

This library provides a pure Python, asynchronous interface for the Telegram Bot API. It's compatible with Python versions 3.8+.

In addition to the pure API implementation, this library features a number of high-level classes to make the development of bots easy and straightforward. These classes are contained in the telegram.ext submodule.

A pure API implementation without telegram.ext is available as the standalone package python-telegram-bot-raw. See here for details.

Note

Installing both python-telegram-bot and python-telegram-bot-raw in conjunction will result in undesired side-effects, so only install one of both.

Telegram API support

All types and methods of the Telegram Bot API 7.2 are supported.

Installing

You can install or upgrade python-telegram-bot via

$ pip install python-telegram-bot --upgrade

To install a pre-release, use the --pre flag in addition.

You can also install python-telegram-bot from source, though this is usually not necessary.

$ git clone https://github.com/python-telegram-bot/python-telegram-bot
$ cd python-telegram-bot
$ python setup.py install

Verifying Releases

We sign all the releases with a GPG key. The signatures are uploaded to both the GitHub releases page and the PyPI project and end with a suffix .asc. Please find the public keys here. The keys are named in the format <first_version>-<last_version>.gpg or <first_version>-current.gpg if the key is currently being used for new releases.

In addition, the GitHub release page also contains the sha1 hashes of the release files in the files with the suffix .sha1.

This allows you to verify that a release file that you downloaded was indeed provided by the python-telegram-bot team.

Dependencies & Their Versions

python-telegram-bot tries to use as few 3rd party dependencies as possible. However, for some features using a 3rd party library is more sane than implementing the functionality again. As these features are optional, the corresponding 3rd party dependencies are not installed by default. Instead, they are listed as optional dependencies. This allows to avoid unnecessary dependency conflicts for users who don't need the optional features.

The only required dependency is httpx ~= 0.27 for telegram.request.HTTPXRequest, the default networking backend.

python-telegram-bot is most useful when used along with additional libraries. To minimize dependency conflicts, we try to be liberal in terms of version requirements on the (optional) dependencies. On the other hand, we have to ensure stability of python-telegram-bot, which is why we do apply version bounds. If you encounter dependency conflicts due to these bounds, feel free to reach out.

Optional Dependencies

PTB can be installed with optional dependencies:

  • pip install "python-telegram-bot[passport]" installs the cryptography>=39.0.1 library. Use this, if you want to use Telegram Passport related functionality.
  • pip install "python-telegram-bot[socks]" installs httpx[socks]. Use this, if you want to work behind a Socks5 server.
  • pip install "python-telegram-bot[http2]" installs httpx[http2]. Use this, if you want to use HTTP/2.
  • pip install "python-telegram-bot[rate-limiter]" installs aiolimiter~=1.1.0. Use this, if you want to use telegram.ext.AIORateLimiter.
  • pip install "python-telegram-bot[webhooks]" installs the tornado~=6.4 library. Use this, if you want to use telegram.ext.Updater.start_webhook/telegram.ext.Application.run_webhook.
  • pip install "python-telegram-bot[callback-data]" installs the cachetools~=5.3.3 library. Use this, if you want to use arbitrary callback_data.
  • pip install "python-telegram-bot[job-queue]" installs the APScheduler~=3.10.4 library and enforces pytz>=2018.6, where pytz is a dependency of APScheduler. Use this, if you want to use the telegram.ext.JobQueue.

To install multiple optional dependencies, separate them by commas, e.g. pip install "python-telegram-bot[socks,webhooks]".

Additionally, two shortcuts are provided:

  • pip install "python-telegram-bot[all]" installs all optional dependencies.
  • pip install "python-telegram-bot[ext]" installs all optional dependencies that are related to telegram.ext, i.e. [rate-limiter, webhooks, callback-data, job-queue].

Quick Start

Our Wiki contains an Introduction to the API explaining how the pure Bot API can be accessed via python-telegram-bot. Moreover, the Tutorial: Your first Bot gives an introduction on how chatbots can be easily programmed with the help of the telegram.ext module.

Resources

  • The package documentation is the technical reference for python-telegram-bot. It contains descriptions of all available classes, modules, methods and arguments as well as the changelog.
  • The wiki is home to number of more elaborate introductions of the different features of python-telegram-bot and other useful resources that go beyond the technical documentation.
  • Our examples section contains several examples that showcase the different features of both the Bot API and python-telegram-bot. Even if it is not your approach for learning, please take a look at echobot.py. It is the de facto base for most of the bots out there. The code for these examples is released to the public domain, so you can start by grabbing the code and building on top of it.
  • The official Telegram Bot API documentation is of course always worth a read.

Getting help

If the resources mentioned above don't answer your questions or simply overwhelm you, there are several ways of getting help.

  1. We have a vibrant community of developers helping each other in our Telegram group. Join us! Asking a question here is often the quickest way to get a pointer in the right direction.
  2. Ask questions by opening a discussion.
  3. You can even ask for help on Stack Overflow using the python-telegram-bot tag.

Concurrency

Since v20.0, python-telegram-bot is built on top of Pythons asyncio module. Because asyncio is in general single-threaded, python-telegram-bot does currently not aim to be thread-safe. Noteworthy parts of python-telegram-bots API that are likely to cause issues (e.g. race conditions) when used in a multi-threaded setting include:

  • telegram.ext.Application/Updater.update_queue
  • telegram.ext.ConversationHandler.check/handle_update
  • telegram.ext.CallbackDataCache
  • telegram.ext.BasePersistence
  • all classes in the telegram.ext.filters module that allow to add/remove allowed users/chats at runtime

Contributing

Contributions of all sizes are welcome. Please review our contribution guidelines to get started. You can also help by reporting bugs or feature requests.

Donating

Occasionally we are asked if we accept donations to support the development. While we appreciate the thought, maintaining PTB is our hobby, and we have almost no running costs for it. We therefore have nothing set up to accept donations. If you still want to donate, we kindly ask you to donate to another open source project/initiative of your choice instead.

License

You may copy, distribute and modify the software provided that modifications are described and licensed for free under LGPL-3. Derivatives works (including modifications or anything statically linked to the library) can only be redistributed under LGPL-3, but applications that use the library don't have to be.

python-telegram-bot's People

Contributors

aelkheir avatar bibo-joshi avatar clot27 avatar dependabot[bot] avatar eldinnie avatar ergoz avatar evgfilim1 avatar franciscod avatar harshil21 avatar ihoru avatar jeffffc avatar jh0ker avatar jlmadurga avatar jonowo avatar josxa avatar jsmnbom avatar leandrotoledo avatar lemontree210 avatar n5y avatar nonegg avatar octonezd avatar ollmer avatar poolitzer avatar pre-commit-ci[bot] avatar rahiel avatar revolter avatar shelomentsevd avatar starry-shivam avatar tsnoam avatar zeshuaro 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

python-telegram-bot's Issues

sendDocument seems to damage the file

Hi Leandro,

First a Big Thanks for the great work!!! But I did find a bug.
When I use
bot.sendDocument(chat_id=chat_id, document=open('xxx.pdf', 'r'))
It give the download, but the file is only 2kb and not readable.
I asked a other user in the telegram.Bot group and he confirmed the problem. Can you have a look at it please?

command handler pull requests #47 and #51

I noticed that there are two command handlers now. The EnhancedBot from mASOUDd in #47 and command_handler.py from me in #51.

I want to discuss what you guys think of the two. And maybe look at some way to combine them so that there is only one command handler in the package.

some of the main differences are:

The way to create the command handler.
EnhancedBot:

you just create a bot and all the tools are in it.

command_handler:

you create a new class with inherits CommandHandler or CommandHandlerWithHelp.
CommandHandler has a self.bot attribute.

The way to create a command.
EnhancedBot:

To create a command you simply do this.

bot = EnhancedBot(token=token)
@bot.command('/bla')
def some_name(command,user_id):
    return ("bla"), None, None)

(I personally love this system as well but I didn't know how to make it.)

command_handler:

create a new method in your class. which starts with 'command_' and takes update.

class myHandler(CommandHandlerWithHelp):
    def command_bla(self, update):
        chat_id = update.message.chat.id
        self.bot.sendMessage(chat_id, 'bla') 
The way to start the command handler.

but I think this is less important because they do basically the same thing here.

EnhancedBot:
while True:
     bot.processUpdates()
     time.sleep(3)
command_handler:
bot = telegram.Bot(token=token)
my_command_handler = myHandler(bot)
my_command_handler.run()  # every command is a new thread.

My opinion.

to it as usable as possible to me it has the following requirements:
I implemented some of these in my command_handler

  • have an easy way to write a method and have that automatically detected as a command and that particular method is run when the command is sent to the bot.
  • As a response be able to make use of the whole telegram api. Now and in the future. (E.G. send a video as response)
  • blocking statements should be handled by the command handler.
  • If I run a bot it should run until I and only I stop it. and not when a error is raised in a command.
  • I want to be able to send arguments with my command

Better documentation of best practices for error handling

It would be useful to add a section to the documentation dealing with error handling. There are certain issues that can lead to errors that may not be immediately obvious.

Example: What happens when a user deletes a chat before the bot has responded? I think it produces a Telegram server error, but what is the best way to deal with this situation safely without crashing the bot.

ability to use custom filename in sendDocument etc.

I have a code that sends txt file, i need use tmp files that have bad names, when i use

temp_file = tempfile.NamedTemporaryFile(delete=False, mode='w')
tmp_filename = temp_file.name
temp_file.write(build_log)
temp_file.close()
document = open(tmp_filename, 'rb')
self.BOT.sendDocument(chat_id=chat_id, document=document)
document.close()
os.unlink(tmp_filename)

in telegram file have dynamicly generated tmp name (like tempsx8eth). How to set custom name?
As i understand we need to refactor class InputFile(object) on line 70

self.filename = os.path.basename(self.input_file.name)

I've seen 1-2 bots that have ability to change sending name and it is very usefull.

Enable logging

Right now methods doesn't log nothing, it makes debugging even harder. A decorator method can make it easier, set log levels by the main method init(debug=(None|INFO|DEBUG)).

API updates: 8th Oct, 2015

October 8, 2015

  • Added initial channel support for bots (no Telegram clients support this at the moment, please wait for updates):
  • The Chat field in the Message is now of the new type Chat.
  • You can now pass a channel username (in the format @channelusername) in the place of chat_id in all methods (and instead of from_chat_id in forwardMessage). For this to work, the bot must be an administrator in the channel (and that‘s exactly what Telegram clients don’t support yet — adding bots as administrators coming soon).

https://core.telegram.org/bots/api-changelog

New object Voice and sendVoice method

Seems like the API has been changed the key 'audio' to 'voice':

1:  {
  update_id: 129566728
  message: {
    message_id: 9972
    from: {
      id: 12173560
      first_name: "Leandro"
      last_name: "S."
      username: "leandrotoledo"
    }-
  chat: {
    id: 12173560
    first_name: "Leandro"
    last_name: "S."
    username: "leandrotoledo"
  }-
  date: 1439815858
    voice: {
      duration: 0
      mime_type: "audio/ogg"
      file_id: "AwADAQADLgEAAvjAuQABIc7Q7q6ncOoC"
      file_size: 9199
    }-
  }-
}

Printing an update isn't too pretty

Due to the top-down .to_json() approach, all the double quotes get applied and escaped recursively. Example result of calling str(update), where update is for example bot.getUpdates()[0].

{"message": "{\"from\": \"{\\\"id\\\": 1234567890, \\\"first_name\\\": \\\"Somebody\\\", \\\"username\\\": \\\"somebody\\\"}\", \"chat\": \"{\\\"id\\\": 45858904, \\\"first_name\\\": \\\"Somebody\\\", \\\"username\\\": \\\"somebody\\\"}\", \"message_id\": 7, \"text\": \"s\", \"date\": 1437171749}", "update_id": 532670696}

Proposed solution: Add datafy, to_data or to_dict method to each data container class that is called top-down instead and define to_json as:

def to_json(self):
    return json.dumps(self.to_data())

Edit: I would probably add this method in a new base class named telegram.DataContainer and make to_data abstract.

Error HTTP 502 in long polling (bot.getUpdates)

Sometimes, I get 502 when calling bot.getUpdates() method.

Log:

2015-08-18 14:11:01,642 ERROR STDERR - Traceback (most recent call last):
2015-08-18 14:11:01,642 ERROR STDERR - File "../../python-telegram-bot/telegram/bot.py", line 621, in _requestUrl
2015-08-18 14:11:01,643 ERROR STDERR - ).read()
2015-08-18 14:11:01,643 ERROR STDERR - File "/usr/lib/python3.4/urllib/request.py", line 153, in urlopen
2015-08-18 14:11:01,643 ERROR STDERR - return opener.open(url, data, timeout)
2015-08-18 14:11:01,643 ERROR STDERR - File "/usr/lib/python3.4/urllib/request.py", line 461, in open
2015-08-18 14:11:01,644 ERROR STDERR - response = meth(req, response)
2015-08-18 14:11:01,644 ERROR STDERR - File "/usr/lib/python3.4/urllib/request.py", line 571, in http_response
2015-08-18 14:11:01,644 ERROR STDERR - 'http', request, response, code, msg, hdrs)
2015-08-18 14:11:01,644 ERROR STDERR - File "/usr/lib/python3.4/urllib/request.py", line 499, in error
2015-08-18 14:11:01,645 ERROR STDERR - return self._call_chain(_args)
2015-08-18 14:11:01,645 ERROR STDERR - File "/usr/lib/python3.4/urllib/request.py", line 433, in _call_chain
2015-08-18 14:11:01,645 ERROR STDERR - result = func(_args)
2015-08-18 14:11:01,645 ERROR STDERR - File "/usr/lib/python3.4/urllib/request.py", line 579, in http_error_default
2015-08-18 14:11:01,646 ERROR STDERR - raise HTTPError(req.full_url, code, msg, hdrs, fp)
2015-08-18 14:11:01,646 ERROR STDERR - urllib.error
2015-08-18 14:11:01,646 ERROR STDERR - .
2015-08-18 14:11:01,646 ERROR STDERR - HTTPError
2015-08-18 14:11:01,646 ERROR STDERR - :
2015-08-18 14:11:01,646 ERROR STDERR - HTTP Error 502: Bad Gateway
2015-08-18 14:11:01,647 ERROR STDERR -
2015-08-18 14:11:01,647 ERROR STDERR - During handling of the above exception, another exception occurred:
2015-08-18 14:11:01,647 ERROR STDERR - Traceback (most recent call last):
2015-08-18 14:11:01,647 ERROR STDERR - File "main.py", line 25, in handleUpdate
2015-08-18 14:11:01,647 ERROR STDERR - for update in bot.getUpdates(offset=lastUpdateID + 1, timeout=120):
2015-08-18 14:11:01,647 ERROR STDERR - File "../../python-telegram-bot/telegram/bot.py", line 79, in decorator
2015-08-18 14:11:01,647 ERROR STDERR - result = func(self, _args, *_kwargs)
2015-08-18 14:11:01,648 ERROR STDERR - File "../../python-telegram-bot/telegram/bot.py", line 120, in decorator
2015-08-18 14:11:01,648 ERROR STDERR - return func(self, _args, *_kwargs)
2015-08-18 14:11:01,648 ERROR STDERR - File "../../python-telegram-bot/telegram/bot.py", line 546, in getUpdates
2015-08-18 14:11:01,648 ERROR STDERR - json_data = self._requestUrl(url, 'POST', data=data)
2015-08-18 14:11:01,648 ERROR STDERR - File "../../python-telegram-bot/telegram/bot.py", line 623, in _requestUrl
2015-08-18 14:11:01,649 ERROR STDERR - raise TelegramError(str(e))
2015-08-18 14:11:01,649 ERROR STDERR - telegram.error
2015-08-18 14:11:01,649 ERROR STDERR - .
2015-08-18 14:11:01,649 ERROR STDERR - TelegramError
2015-08-18 14:11:01,649 ERROR STDERR - :
2015-08-18 14:11:01,649 ERROR STDERR - HTTP Error 502: Bad Gateway
2015-08-18 14:11:01,650 ERROR STDERR -
2015-08-18 14:11:01,650 ERROR STDERR - During handling of the above exception, another exception occurred:
2015-08-18 14:11:01,650 ERROR STDERR - Traceback (most recent call last):
2015-08-18 14:11:01,650 ERROR STDERR - File "main.py", line 90, in
2015-08-18 14:11:01,650 ERROR STDERR - lastUpdateID = handleUpdate(bot, lastUpdateID)
2015-08-18 14:11:01,650 ERROR STDERR - File "main.py", line 54, in handleUpdate
2015-08-18 14:11:01,650 ERROR STDERR - except urllib.HTTPError as httpErr:
2015-08-18 14:11:01,651 ERROR STDERR - AttributeError
2015-08-18 14:11:01,651 ERROR STDERR - :

Access to audio file object

As you know we can get an audio object using message.audio but this obj is contains a dictionary and some information about the fie,But how can I access to an audio file object? I mean its file for example save it and access to its ogg for mat or directly access to this file?

Unable to JSON serialize forwarded messages

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/rq/worker.py", line 558, in perform_job
    rv = job.perform()
  File "/usr/local/lib/python2.7/dist-packages/rq/job.py", line 495, in perform
    self._result = self.func(*self.args, **self.kwargs)
  File "/home/joker/projects/bot/operations.py", line 50, in handle_update
    handle_command(text, message)
  File "/home/joker/projects/bot/operations.py", line 77, in handle_command
    result = getattr(botcommands, command)(message, debug=debug)
  File "/home/joker/projects/bot/config.py", line 85, in wrapper
    MQTT['topic'], payload=msg.to_json(),
  File "/usr/local/lib/python2.7/dist-packages/telegram/base.py", line 40, in to_json
    return json.dumps(self.to_dict())
  File "/usr/lib/python2.7/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "/usr/lib/python2.7/json/encoder.py", line 201, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python2.7/json/encoder.py", line 264, in iterencode
    return _iterencode(o, 0)
  File "/usr/lib/python2.7/json/encoder.py", line 178, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <telegram.user.User object at 0xf44c50> is not JSON serializable

Force close if client send Sticker to bot

i have some isue if someone send sticker to my bot, thats make my bot force close
i use python-telegram-bot/examples/echobot.py
Traceback (most recent call last):

File "examples/echobot.py", line 271, in
echo()
File "examples/echobot.py", line 59, in echo
message = update.message.text.encode('utf-8')
AttributeError: 'NoneType' object has no attribute 'encode'

thanks before

sendVideo by file_id doesn't return file_size

When sending a video by file_id it doesn't return back a message within the file_size.
API says it's a Optional field, although it's not same behavior as sending audio by file_id.

Audio:

{u'performer': u'Leandro Toledo', u'title': u'Teste', u'file_id': u'BQADAQADwwcAAjU8LQdBRsl3_qD2TAI', u'file_size': 28232, u'duration': 4, u'mime_type': u'audio/mpeg'}

Video:

{u'duration': 4, u'width': 360, u'file_id': u'BAADAQADIgEAAvjAuQABOuTB937fPTgC', u'thumb': {u'width': 50, u'height': 90, u'file_id': u'AAQBABOyGNspAAR5UwzHfwz0GBU3AAIC', u'file_size': 821}, u'height': 640}

This is probably a bug on API side, I've notified @botsupport, waiting for their reply.

can't pickle lock objects

As stated by @JokerQyou the recent version doesn't allow to pickle objects::
>>> pickle.dump(bot, open('save.p', 'wb'))

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/pickle.py", line 1370, in dump
    Pickler(file, protocol).dump(obj)
  File "/usr/lib/python2.7/pickle.py", line 224, in dump
    self.save(obj)
  File "/usr/lib/python2.7/pickle.py", line 331, in save
    self.save_reduce(obj=obj, *rv)
  File "/usr/lib/python2.7/pickle.py", line 419, in save_reduce
    save(state)
  File "/usr/lib/python2.7/pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "/usr/lib/python2.7/pickle.py", line 649, in save_dict
    self._batch_setitems(obj.iteritems())
  File "/usr/lib/python2.7/pickle.py", line 663, in _batch_setitems
    save(v)
  File "/usr/lib/python2.7/pickle.py", line 331, in save
    self.save_reduce(obj=obj, *rv)
  File "/usr/lib/python2.7/pickle.py", line 419, in save_reduce
    save(state)
  File "/usr/lib/python2.7/pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "/usr/lib/python2.7/pickle.py", line 649, in save_dict
    self._batch_setitems(obj.iteritems())
  File "/usr/lib/python2.7/pickle.py", line 663, in _batch_setitems
    save(v)
  File "/usr/lib/python2.7/pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "/usr/lib/python2.7/pickle.py", line 600, in save_list
    self._batch_appends(iter(obj))
  File "/usr/lib/python2.7/pickle.py", line 615, in _batch_appends
    save(x)
  File "/usr/lib/python2.7/pickle.py", line 331, in save
    self.save_reduce(obj=obj, *rv)
  File "/usr/lib/python2.7/pickle.py", line 419, in save_reduce
    save(state)
  File "/usr/lib/python2.7/pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "/usr/lib/python2.7/pickle.py", line 649, in save_dict
    self._batch_setitems(obj.iteritems())
  File "/usr/lib/python2.7/pickle.py", line 663, in _batch_setitems
    save(v)
  File "/usr/lib/python2.7/pickle.py", line 331, in save
    self.save_reduce(obj=obj, *rv)
  File "/usr/lib/python2.7/pickle.py", line 419, in save_reduce
    save(state)
  File "/usr/lib/python2.7/pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "/usr/lib/python2.7/pickle.py", line 649, in save_dict
    self._batch_setitems(obj.iteritems())
  File "/usr/lib/python2.7/pickle.py", line 663, in _batch_setitems
    save(v)
  File "/usr/lib/python2.7/pickle.py", line 306, in save
    rv = reduce(self.proto)
  File "/home/leandrotoledo/workspace/python-telegram-bot/env/lib/python2.7/copy_reg.py", line 70, in _reduce_ex
    raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle lock objects

Mostly because nested classes, but it needs further investigation.

http proxy support

Hello,

Could you please add proxy support?
As a workaround, now I do smth like:

import telegram
import urllib2

class Bot(telegram.Bot):
    def __init__(self, token, base_url=None, debug=False, proxy={}):
        proxy_handler = urllib2.ProxyHandler(proxy)
        opener = urllib2.build_opener(proxy_handler)
        urllib2.install_opener(opener)
        super(Bot, self).__init__(token, base_url=base_url, debug=debug)

bot = Bot(token='token', proxy=dict(http="http://host:port/"))

InputFile fails to parse JPG header on Python 2.7.3

>>> bot.sendPhoto(chat_id, 'URL')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "telegram/bot.py", line 95, in decorator
    result = func(self, *args, **kwargs)
  File "telegram/bot.py", line 121, in decorator
    json_data = self._requestUrl(url, 'POST', data=data)
  File "telegram/bot.py", line 610, in _requestUrl
    data = InputFile(data)
  File "telegram/inputfile.py", line 66, in __init__
    self.mimetype = InputFile.is_image(self.input_file_content)
  File "telegram/inputfile.py", line 141, in is_image
    re.match(b'\xff\xd8\xff\xe1(.*){2}Exif', header):
  File "/home/leandrotoledo/.pyenv/versions/2.7.3/lib/python2.7/re.py", line 137, in match
    return _compile(pattern, flags).match(string)
  File "/home/leandrotoledo/.pyenv/versions/2.7.3/lib/python2.7/re.py", line 242, in _compile
    raise error, v # invalid expression
sre_constants.error: nothing to repeat

It only occurs on < Python 2.7.3 (reported by @JokerQyou)

ValueError: No JSON object could be decoded

I get crashes every once in awhile with the newest version:

ERROR:root:main loop:
Traceback (most recent call last):
File "./telegram-bot.py", line 485, in main
exit = parse(bot)
File "./telegram-bot.py", line 516, in parse
for update in bot.getUpdates(offset=LAST_UPDATE_ID, timeout=10):
File "/usr/local/lib/python2.7/site-packages/telegram/bot.py", line 123, in decorator
result = func(self, _args, *_kwargs)
File "/usr/local/lib/python2.7/site-packages/telegram/bot.py", line 653, in getUpdates
result = request.post(url, data)
File "/usr/local/lib/python2.7/site-packages/telegram/utils/request.py", line 96, in post
message = _parse(error.read())
File "/usr/local/lib/python2.7/site-packages/telegram/utils/request.py", line 45, in _parse
data = json.loads(json_data.decode())
File "/usr/local/lib/python2.7/json/init.py", line 338, in loads
return _default_decoder.decode(s)
File "/usr/local/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/local/lib/python2.7/json/decoder.py", line 384, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

Exception while parsing HTTPError in request.py post method

getUpdates method raises exception while parsing HTTPError in /utils/request.py post(url, data) method.
It goes to:

    except HTTPError as error:
        if error.getcode() == 403:
            raise TelegramError('Unauthorized')
        if error.getcode() == 502:
            raise TelegramError('Bad Gateway')

        message = _parse(error.read())
        raise TelegramError(message)

But it seems like error.read() returns not a JSON-string so while parsing this with json.loads(json_data.decode()) exception ValueError: Expecting value: line 1 column 1 (char 0) appears.

Ensure encoding consistence

Telegram API speaks UTF-8, but does Unicode. We need to ensure encoding consistence when sending/receiving messages/files.

Update_ID

Hello, could the update_id function be implemented? Otherwise i'm not able to see when to send a message?

getting music?

I searched the whole documentation but didnt find anything so I ask you: is it possible to download mp3 files sent to the bot? thx :)

sendDocument does file_content.encode()?

When I call sendDocument() with file which is already binary (mode="rb"), it tries to encode it once more. So if the file content is containing non-ascii byte, it faild with:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128)

This is caused by here.
in inputfile.py line 90:

    def _parse(self, form):
        if sys.version_info > (3,):
            # on Python 3 form needs to be byte encoded
            encoded_form = []
            for item in form:
                try:
                    encoded_form.append(item.encode())
                except AttributeError:
                    encoded_form.append(item)

            return b'\r\n'.join(encoded_form)
        return '\r\n'.join(form)

getitem method for User objects

message.from_user returns a User object, which has username, first name, last name and ID fields. However, these can't be accessed by ob["username"] because there is no getitem method for User class.

Disable logging

Create a setting that allows you to disable logging output to the screen.
Even disabled debug, the program sends information messages to the screen.

2015-07-29 17:25:49,424 - telegram.bot - INFO - Starting bot @xxxxxxx_bot
2015-07-29 17:25:50,621 - telegram.bot - INFO - Getting updates: [434449746, 435444747, 444449748, 435444449, 4358444440, 4344444751, 4354444452]

video.py to_dict

'video':str(message.video) if hasattr(message,'video') else None,
File "modules\telegram\base.py", line 30, in str
return str(self.to_dict())
File "modules\telegram\video.py", line 62, in to_dict
data['thumb'] = self.thumb.to_dict()
AttributeError: 'unicode' object has no attribute 'to_dict'

Unicode compatibility issue

I found this bug while testing out my simple echo script. If I send a message in Korean, I don't get any echos back, but instead I start getting a constant stream of 500 internal server errors in the GAE log. Please see the following traceback. (Copy & paste loses all formatting, so the full traceback is in a screenshot.)


File "/base/data/home/apps/s~research-bot-for-telegram/1.386316310470646493/venv/Lib/site-packages/telegram/bot.py", line 604, in _requestUrl
urlencode(data).encode()
File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib.py", line 1307, in urlencode
v = quote_plus(str(v))
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)


2015-08-09_221616 gae unicode error traceback

Telegram would keep trying to resend the message (and keep failing), until I turned off echo and instead send back some generic English text.

Telegram Bot API changes (July 2015)

As listed on Bot API changelog - https://core.telegram.org/bots/api-changelog

The following changes have been made on Telegram Bot API:

  • The thumb field is now optional for Video, Sticker and Document objects
  • The API now supports both video and photo captions. The caption field has been removed from the Video object and added to the Message object instead.
  • caption and duration optional fields have been added to the sendVideo method.

echobot example crashes because of byte encoded strings (python3)

Hi,
In the example echobot.py, the string to be sent is converted to bytes with .encode('utf-8') but the json.dumps() function cannot handle this. I suspect this to be a python3 issue. Can I just remove the encode() ?

 File "echobot.py", line 50, in <module>
    main()
  File "echobot.py", line 28, in main
    echo(bot)
  File "echobot.py", line 43, in echo
    bot.sendMessage(chat_id=chat_id,text=message)
  File "/usr/local/lib/python3.4/dist-packages/telegram/bot.py", line 126, in decorator
    result = func(self, *args, **kwargs)
  File "/usr/local/lib/python3.4/dist-packages/telegram/bot.py", line 158, in decorator
    result = request.post(url, data)
  File "/usr/local/lib/python3.4/dist-packages/telegram/utils/request.py", line 88, in post
    data = json.dumps(data)
  File "/usr/lib/python3.4/json/__init__.py", line 230, in dumps
    return _default_encoder.encode(obj)
  File "/usr/lib/python3.4/json/encoder.py", line 192, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.4/json/encoder.py", line 250, in iterencode
    return _iterencode(o, 0)
  File "/usr/lib/python3.4/json/encoder.py", line 173, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: b'test' is not JSON serializable

Nice work btw!

Uncaught exception

File "py-bot.py", line 102, in
updates = bot.getUpdates(offset=current_offset, limit=100, timeout=60)
File "/Library/Python/2.7/site-packages/telegram/bot.py", line 537, in getUpdates
return [Update.de_json(x) for x in data]
File "/Library/Python/2.7/site-packages/telegram/update.py", line 15, in de_json
message = Message.de_json(data['message'])
File "/Library/Python/2.7/site-packages/telegram/message.py", line 139, in de_json
chat=chat,
UnboundLocalError: local variable 'chat' referenced before assignment

How to get last unread message, bot.getUpdates()[-1].update_id - return last received message

How to get last unread message?

in examples:
try:
LAST_UPDATE_ID = bot.getUpdates()[-1].update_id
except IndexError:
LAST_UPDATE_ID = None

bot.getUpdates()[-1].update_id - return last received message

This code solves the problem, but bot.getUpdates () runs 2 times
try:
bot.getUpdates()[-len(bot.getUpdates())].update_id
except IndexError:
LAST_UPDATE_ID = None

p.s.
in the examples have this code
try:
LAST_UPDATE_ID = bot.getUpdates()[-1].update_id
except IndexError:
LAST_UPDATE_ID = None
...
for update in bot.getUpdates(offset=LAST_UPDATE_ID):
if LAST_UPDATE_ID < update.update_id:
BUT LAST_UPDATE_ID the same update.update_id, if you run a bot there are new unread messages

echobot.py gives IndexError: list index out of range

After inserting my token I did run the echobot.py

It gives me the following error

Traceback (most recent call last):
File "", line 1, in
LAST_UPDATE_ID = bot.getUpdates()[-1].update_id
IndexError: list index out of range

What can I try to debug this?

Logging exception

Basically I'm receiving messages in italian, and we have various characters that are not included in the ascii table such as: é, ó, à, í, ú, etc.
Bear in mind that I am not using a filehandler to write the log but since I'm on uwsgi I'm using a StreamHandler and I cannot pass the encoding to the StreamHandler

This is the log:

2015-10-10 10:04:28,708|DEBUG |14345|telegram.bot|bot|Entering: sendMessage --- Logging error --- Traceback (most recent call last): File "/usr/lib/python3.4/logging/__init__.py", line 966, in emit stream.write(msg) UnicodeEncodeError: 'ascii' codec can't encode character '\xe8' in position 548: ordinal not in range(128) Call stack: File "/home/shevraar/dev/venv/jovabot/lib/python3.4/site-packages/flask/app.py", line 1836, in __call__ return self.wsgi_app(environ, start_response) File "/home/shevraar/dev/venv/jovabot/lib/python3.4/site-packages/flask/app.py", line 1817, in wsgi_app response = self.full_dispatch_request() File "/home/shevraar/dev/venv/jovabot/lib/python3.4/site-packages/flask/app.py", line 1475, in full_dispatch_request rv = self.dispatch_request() File "/home/shevraar/dev/venv/jovabot/lib/python3.4/site-packages/flask/app.py", line 1461, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "./jovabot/__init__.py", line 115, in telegram_hook jova_do_something(update.message) File "./jovabot/__init__.py", line 76, in jova_do_something parse_mode=parse_mode) File "/home/shevraar/dev/venv/jovabot/lib/python3.4/site-packages/telegram/bot.py", line 127, in decorator logger.debug(result) Message: <telegram.message.Message object at 0x7fde9bfcafd0> Arguments: () 2015-10-10 10:04:29,173|DEBUG |14345|telegram.bot|bot|Exiting: sendMessage

Thank you

Get phone number

Dear Leandro,
I wonder how to get the user's phone number that sent a message to the bot.

Make tests more generic

The way it is right now it will fail if not ToledosPalaceBot, if more generic Travis could run all the tests when pull requesting, etc.

error when trying get first_name or other data from update.message.from

error when trying get first_name or other data from update.message.from
print update['message']['from']['first_name']
File "/opt/bot/python-telegram-bot/telegram/base.py", line 17, in getitem
return self.dict[item]
KeyError: 'from'

print update.message.from.first_name
print update.message.from.first_name
^
SyntaxError: invalid syntax

Photos can't be printed

Trying to stringify a message that contains a photo results in the following exception:

Traceback (most recent call last):
  File "E:\Development\Python\codetalkircbot\codegram.py", line 82, in <module>
    main()
  File "E:\Development\Python\codetalkircbot\codegram.py", line 78, in main
    bot.poll_loop(SLEEP)
  File "E:\Development\Python\codetalkircbot\codegram.py", line 67, in poll_loop
    self.handle_updates(updates)
  File "E:\Development\Python\codetalkircbot\codegram.py", line 43, in handle_updates
    print(update)
  File "E:\Development\Python\codetalkircbot\venv\lib\site-packages\telegram\update.py", line 32, in __str__
    return self.to_json()
  File "E:\Development\Python\codetalkircbot\venv\lib\site-packages\telegram\update.py", line 28, in to_json
    json_data['message'] = self.message.to_json()
  File "E:\Development\Python\codetalkircbot\venv\lib\site-packages\telegram\message.py", line 184, in to_json
    json_data['photo'] = self.photo.to_json()
AttributeError: 'list' object has no attribute 'to_json'

Message.photo is a list of PhotoSize objects. Should be easy to handle along with #12.

Problem ssl Violation Protocol

Hello,
i have this error ( random )

Traceback (most recent call last):
File "keliwebBot.py", line 57, in
main()
File "keliwebBot.py", line 28, in main
LAST_UPDATE_ID = bot.getUpdates()[-1].update_id
File "/usr/local/lib/python2.7/site-packages/telegram/bot.py", line 123, in decorator
result = func(self, _args, *_kwargs)
File "/usr/local/lib/python2.7/site-packages/telegram/bot.py", line 653, in getUpdates
result = request.post(url, data)
File "/usr/local/lib/python2.7/site-packages/telegram/utils/request.py", line 91, in post
result = urlopen(request).read()
File "/usr/local/lib/python2.7/urllib2.py", line 154, in urlopen
return opener.open(url, data, timeout)
File "/usr/local/lib/python2.7/urllib2.py", line 431, in open
response = self._open(req, data)
File "/usr/local/lib/python2.7/urllib2.py", line 449, in _open
'_open', req)
File "/usr/local/lib/python2.7/urllib2.py", line 409, in _call_chain
result = func(*args)
File "/usr/local/lib/python2.7/urllib2.py", line 1240, in https_open
context=self._context)
File "/usr/local/lib/python2.7/urllib2.py", line 1197, in do_open
raise URLError(err)
urllib2.URLError: <urlopen error EOF occurred in violation of protocol (_ssl.c:581)>

for solve i have tried to add this code in my script:

import ssl
ssl.PROTOCOL_SSLv23 = ssl.PROTOCOL_TLSv1

and not work.

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.