Giter Site home page Giter Site logo

telepot's Introduction

telepot's People

Contributors

0xmelkor avatar aragaer avatar ayumukasuga avatar boxama avatar das7pad avatar hoskeowl avatar nickoala avatar quasiyoke avatar zumoshi 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

telepot's Issues

Error on CounterBot

I'm trying to test the counter bot but I only get:

"ERROR:root:on_close() called due to NotImplementedError: "

when I send a message.
I don't know what is wrong, I just copied the code and put my Token there.

Sanitisation

Hi Nickoala.

This is a really excelent module and it's been a pleasure to work with...

Just a quick question, Does Telepot or the Telegram API sanitise the input?

I presume it is still vunerable to ddos attacks but wondering if there are any other security measures I need to put in place,

Thanks and looking forward to hearing from you,

TM

can't send file.

  1. I tried to send some files that has korean language. it did not work.
    so changed file name with urllib.request.quote temporarily.
    it works. but it is hard to reconize what the file is.
    Is there any possible way to send file with korean file name, please let me know.
  2. I can't find custom keyboard settings. i want to change size of font, or key block.

glance fails with `Cannot infer content type from message` if emoji in user name

Hello,

so basically put an emoji in your name (doesn't matter first or last) than pm your bot and it explodes :|

reproduction code:

import telepot
bot = telepot.Bot('token')

updates = bot.getUpdates()
for msg in updates:
    content_type, chat_type, chat_id = telepot.glance(msg)
    print(chat_id)

stack trace:

Traceback (most recent call last):
  File "emobug.py", line 6, in <module>
    content_type, chat_type, chat_id = telepot.glance(msg)
  File "C:\Users\Bor\AppData\Local\Programs\Python\Python35\lib\site-packages\telepot\__init__.py", line 68, in glance
    return gl_message()
  File "C:\Users\Bor\AppData\Local\Programs\Python\Python35\lib\site-packages\telepot\__init__.py", line 51, in gl_message
    content_type = _infer_content_type(msg)
  File "C:\Users\Bor\AppData\Local\Programs\Python\Python35\lib\site-packages\telepot\__init__.py", line 44, in _infer_content_type
    raise RuntimeError('Cannot infer content type from message', msg)
RuntimeError: ('Cannot infer content type from message', {'message': {'chat': {'type': 'private', 'first_name': 'Bor', 'last_name': '691\U0001f631', 'id': 61412354, 'username': '------'}, 'date': 1459066867, 'text': 'my name has an emoji', 'message_id': 157, 'from': {'first_name': 'Bor', 'last_name': '691\U0001f631', 'id': 61412354, 'username': '------'}}, 'update_id': 816132183})

the formatting thing from the other issue would've came in handy in here too. i'm looking forward for that one.

thanks in advance


update , seems like i have made a mistake in my reproduction code , and in fact telepot can handle messages with emoji in user name correctly , this is the main trace i got in main project (which i failed miserably in isolating it... )

Traceback (most recent call last):
  File "C:\w\bot\support\src\bot.py", line 23, in index
    bot.handle(cherrypy.request.json['message'])
  File "C:\w\bot\support\src\botsaz.py", line 31, in handle
    content_type, chat_type, chat_id = telepot.glance(msg)
  File "C:\Python34\lib\site-packages\telepot\__init__.py", line 68, in glance
    return gl_message()
  File "C:\Python34\lib\site-packages\telepot\__init__.py", line 51, in gl_message
    content_type = _infer_content_type(msg)
  File "C:\Python34\lib\site-packages\telepot\__init__.py", line 44, in _infer_content_type
    raise RuntimeError('Cannot infer content type from message', msg)
RuntimeError: ('Cannot infer content type from message', {'chat': {'type': 'supergroup', 'id': -1001033794483, 'title': '😍 groupname💦'}, 'date': 1459065099, 'message_id': 3328, 'from': {'first_name': '🔰K E E P E R🔰™', 'username': '(removed)', 'id': 157123872}})

since i recently had other issues with emojis i assumed it was because of emojis in his name , but now that i look closer the json is in fact incomplete and lacks all message types . my bad.
i'll investigate further in my own code to see why it is missing required keys.

How can I call sendMessage in another thread?

Hello.

First of all, thank you for making this great work, I found your framework pretty good, and it's helping me alot.

I've ran into an issue, It's code-related to how can I call it from a thread... I've never worked with threads before, but now I need to receive messages using on_chat_message method and I need to pull data from a website in the same time.

Then I need to save this data do a database and send to registered users after.

So far, I managed to save it do DB working, but I can't send it to users, because I don't know how I can call it inside the getJSON thread...

Can you help a novice with an advice? :)

Here's the code I've so far:

https://gist.github.com/anonymous/b690bfe36bf4f454b49376fa3ac80ff4

Thanks in advance!

Stop listening messages when the script was off

Goog morning!

I would like to know if something has been made to stop Telegram send me old messages when the python script of telepot was off. I need it because it's intended to open doors, and in case something happens that takes my server off, I don't want the software to be opening doors at 3am (when, for example, the server comes back online) while everybody is sleeping.

I explained the issue here but got no answer yet.

Proxy

It lacks the ability to set up a proxy to connect.

Strange problem in "last_name" field

Hi,
I use this framework and I'm very happy :) but today, after some weeks of perfect works, my bot hangs when I try to record [from].[last_name].
The line
lastname_user = msg['from']['last_name']
raise an exception:
Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/telepot/__init__.py", line 379, in handle callback(update['message']) File "tvcc.py", line 101, in handle lastname_user = msg['from']['last_name'] KeyError: 'last_name'

Before today, same code worked correctly.

Anything changed in API or telepot?

Thanks! :)

Error 414 while answering inline query

Hello,
first thanks for making telepot , it made my work a lot easier.

in init.py:316 [answerInlineQuery function] you send the results to requests.post as params rather than post data, therefor its added to the url resulting in a potentially very long url (in my case i have 12 pictures each with up to 200 characters of utf-8 description and a long link) resulting in a 17144 character link!

you can find similar issue with other bot api modules in the following links:
yagop/node-telegram-bot-api#19
irazasyed/telegram-bot-sdk#38

in case it might help here's the url generated

stack trace:

Traceback (most recent call last):
  File "C:\Users\------\AppData\Local\Programs\Python\Python35\lib\site-packages\telepot\__init__.py", line 164, in _parse
    data = response.json()
  File "C:\Users\------\AppData\Local\Programs\Python\Python35\lib\site-packages\requests\models.py", line 808, in json
    return complexjson.loads(self.text, **kwargs)
  File "C:\Users\------\AppData\Local\Programs\Python\Python35\lib\json\__init__.py", line 319, in loads
    return _default_decoder.decode(s)
  File "C:\Users\------\AppData\Local\Programs\Python\Python35\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\------\AppData\Local\Programs\Python\Python35\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\------\AppData\Local\Programs\Python\Python35\lib\site-packages\telepot\__init__.py", line 332, in handle
    callback(update['inline_query'])
  File "C:/Users/------/.../main.py", line 27, in handle_telegram
    bot.answerInlineQuery(query_id, articles)
  File "C:\Users\------\AppData\Local\Programs\Python\Python35\lib\site-packages\telepot\__init__.py", line 319, in answerInlineQuery
    return self._parse(r)
  File "C:\Users\------\AppData\Local\Programs\Python\Python35\lib\site-packages\telepot\__init__.py", line 166, in _parse
    raise BadHTTPResponse(response.status_code, response.text)
telepot.exception.BadHTTPResponse: (414, '<html>\r\n<head><title>414 Request-URI Too Large</title></head>\r\n<body bgcolor="white">\r\n<center><h1>414 Request-URI Too Large</h1></center>\r\n<hr><center>nginx/1.6.2</center>\r\n</body>\r\n</html>\r\n')

it should be easy to fix , just have to change method of sending data from get to post.

since the bot is currently in production (we missed the issue since it only happens in some cases ...) it would be nice if you could fix it as a priority .

thanks in advance.

Is there a Way to "Auto-Hide" a keyboard?

I was wondering if there is a way to auto hide the keyboard when the user press a key, because I can't hide it until the next message and I think that autohide would seem more practical for some simple selection keyboards that I'm using.

Default timeout / WaitTooLong

(some doc feedback)

I ran the example from the Python3 section. I did not set any timeout option, but yet I see those errors:

ERROR:root:on_close() called due to WaitTooLong: 

And the message counter always returns 1.

Although the documentation says:

If the timeout option is set, it will raise a WaitTooLong exception after that many seconds.
If the timeout option is not set or is None (default), it will wait forever.

It's probably a doc/default value adjustement :)

Telepot doesn't handle well to loose connection

Hi,
if the machine where telepot bot is running looses its connection (with telegram) it enters to an infinite loop until it recover connection if it happens:

Traceback (most recent call last):
  File "/home/guillem/.virtualenvs/improviders/lib/python3.4/site-packages/requests/packages/urllib3/connectionpool.py", line 372, in _make_request
    httplib_response = conn.getresponse(buffering=True)
TypeError: getresponse() got an unexpected keyword argument 'buffering'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/guillem/.virtualenvs/improviders/lib/python3.4/site-packages/requests/packages/urllib3/connectionpool.py", line 374, in _make_request
    httplib_response = conn.getresponse()
  File "/usr/lib/python3.4/http/client.py", line 1171, in getresponse
    response.begin()
  File "/usr/lib/python3.4/http/client.py", line 351, in begin
    version, status, reason = self._read_status()
  File "/usr/lib/python3.4/http/client.py", line 313, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "/usr/lib/python3.4/socket.py", line 374, in readinto
    return self._sock.recv_into(b)
  File "/usr/lib/python3.4/ssl.py", line 769, in recv_into
    return self.read(nbytes, buffer)
  File "/usr/lib/python3.4/ssl.py", line 641, in read
    v = self._sslobj.read(len, buffer)
socket.timeout: The read operation timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/guillem/.virtualenvs/improviders/lib/python3.4/site-packages/requests/adapters.py", line 370, in send
    timeout=timeout
  File "/home/guillem/.virtualenvs/improviders/lib/python3.4/site-packages/requests/packages/urllib3/connectionpool.py", line 597, in urlopen
    _stacktrace=sys.exc_info()[2])
  File "/home/guillem/.virtualenvs/improviders/lib/python3.4/site-packages/requests/packages/urllib3/util/retry.py", line 245, in increment
    raise six.reraise(type(error), error, _stacktrace)
  File "/home/guillem/.virtualenvs/improviders/lib/python3.4/site-packages/requests/packages/urllib3/packages/six.py", line 310, in reraise
    raise value
  File "/home/guillem/.virtualenvs/improviders/lib/python3.4/site-packages/requests/packages/urllib3/connectionpool.py", line 544, in urlopen
    body=body, headers=headers)
  File "/home/guillem/.virtualenvs/improviders/lib/python3.4/site-packages/requests/packages/urllib3/connectionpool.py", line 376, in _make_request
    self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
  File "/home/guillem/.virtualenvs/improviders/lib/python3.4/site-packages/requests/packages/urllib3/connectionpool.py", line 304, in _raise_timeout
    raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)
requests.packages.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='api.telegram.org', port=443): Read timed out. (read timeout=50)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/guillem/metis/repos/telepot/telepot/__init__.py", line 356, in get_from_telegram_server
    result = self.getUpdates(offset=offset, timeout=timeout)
  File "/home/guillem/metis/repos/telepot/telepot/__init__.py", line 280, in getUpdates
    timeout=self._http_timeout+(0 if timeout is None else timeout))
  File "/home/guillem/.virtualenvs/improviders/lib/python3.4/site-packages/requests/api.py", line 108, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "/home/guillem/.virtualenvs/improviders/lib/python3.4/site-packages/requests/api.py", line 50, in request
    response = session.request(method=method, url=url, **kwargs)
  File "/home/guillem/.virtualenvs/improviders/lib/python3.4/site-packages/requests/sessions.py", line 464, in request
    resp = self.send(prep, **send_kwargs)
  File "/home/guillem/.virtualenvs/improviders/lib/python3.4/site-packages/requests/sessions.py", line 576, in send
    r = adapter.send(request, **kwargs)
  File "/home/guillem/.virtualenvs/improviders/lib/python3.4/site-packages/requests/adapters.py", line 433, in send
    raise ReadTimeout(e, request=request)
requests.exceptions.ReadTimeout: HTTPSConnectionPool(host='api.telegram.org', port=443): Read timed out. (read timeout=50)
Traceback (most recent call last):
  File "/home/guillem/.virtualenvs/improviders/lib/python3.4/site-packages/requests/packages/urllib3/connectionpool.py", line 544, in urlopen
    body=body, headers=headers)
  File "/home/guillem/.virtualenvs/improviders/lib/python3.4/site-packages/requests/packages/urllib3/connectionpool.py", line 341, in _make_request
    self._validate_conn(conn)
  File "/home/guillem/.virtualenvs/improviders/lib/python3.4/site-packages/requests/packages/urllib3/connectionpool.py", line 762, in _validate_conn
    conn.connect()
  File "/home/guillem/.virtualenvs/improviders/lib/python3.4/site-packages/requests/packages/urllib3/connection.py", line 204, in connect
    conn = self._new_conn()
  File "/home/guillem/.virtualenvs/improviders/lib/python3.4/site-packages/requests/packages/urllib3/connection.py", line 134, in _new_conn
    (self.host, self.port), self.timeout, **extra_kw)
  File "/home/guillem/.virtualenvs/improviders/lib/python3.4/site-packages/requests/packages/urllib3/util/connection.py", line 64, in create_connection
    for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
  File "/usr/lib/python3.4/socket.py", line 533, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known

During handling of the above exception, another exception occurred:

(and repeat ReadTimeoutError exception + socket.gaierror again and again)

The problem is this loop that doesn't have any end condition.

Before start a PR, is this situation expected to be managed in some way?
My solution will be to have a new param in notifyOnMessage() with the number of attempts (by default, 5, for example).
In the except (or finally) of the loop, it discounts an attempt and if it is less or equal to 0 it breaks the loop.
It should stop the main thread which can be done sending an interruption signal to main thread:

os.kill(os.getpid(), signal.SIGINT)

Scheduling

It is complicated to add periodic task to bot, when bot running message loop.
Did you think about add possibility of scheduling tasks?
Like "every day at 10:00 send a message to ... "
A config may be like django-celery (http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html) or something like that is good enough i think.
Or maybe you can took me advise how to make it?
P.S. Sorry about writing this question to "Issues" but i really can't found any information about this.

bot.notifyOnMessage(handle) (self handel set message as read.)

Hello Nick Lee,

I realy love this script.
i'm working on this to control my PI.

But i am new to python and dont know how to handle at this point.
i'm working from the diceyclock.py

i have a command /reboot this works only the problem is that the message is not set read so when i start the script it wil reboot again and again.

i lookt in to init.py from telepot and found get_from_telegram_server() and see that it wil set the message as read (offset). But how can i implement it on this :

if command == '/restart':
    -- line to set message as read -- 
    bot.sendMessage(chat_id, str("rebooting in 3"))
    time.sleep(1)
    bot.sendMessage(chat_id, str("2"))
    time.sleep(1)
    bot.sendMessage(chat_id, str("1"))
    time.sleep(1)
    restart()

bot to chk activity over a particular period

a bot that when called will look at the whole chat in a particular group and report the active users during a particular time , and then report the people in the group who did not participate during a particular time period from the list of group's users. Can this be done? How to go about it

pypi version very old ?

Just so that you know... The package seems to be outdated on pypi and fails on install :)

pip install telebot
Downloading/unpacking telebot
  Downloading telebot-0.0.2.tar.gz
  Storing download in cache at /home/mathieu/Downloads/pip/https%3A%2F%2Fpypi.python.org%2Fpackages%2Fsource%2Ft%2Ftelebot%2Ftelebot-0.0.2.tar.gz
  Running setup.py (path:/tmp/pip-build-j0hVco/telebot/setup.py) egg_info for package telebot
    Traceback (most recent call last):
      File "<string>", line 17, in <module>
      File "/tmp/pip-build-j0hVco/telebot/setup.py", line 6, in <module>
        readme = open('README.md').read()
    IOError: [Errno 2] No such file or directory: 'README.md'
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):

  File "<string>", line 17, in <module>

  File "/tmp/pip-build-j0hVco/telebot/setup.py", line 6, in <module>

    readme = open('README.md').read()

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

----------------------------------------
Cleaning up...
Command python setup.py egg_info failed with error code 1 in /tmp/pip-build-j0hVco/telebot
Storing debug log for failure in /home/mathieu/.pip/pip.log

Need some help (force delegator bot end)

I need an easy way to force the end of a Delegator class instance. For example, imagine I want to use "/end" to force disconnection. I'm not very keen on python 3 and a little bit lost. Is it enough with throwing an exception? Thanks in advance.

could't send a *.wav file

Hello,
the command "bot.sendAudio(chat_id, open('dgdg.mp3', 'rb'), title='Ringtone')" can't send a wav- file.
It returns the follow error- message on a RPI.

    bot.sendAudio(ChatId, open(sys.argv[2], 'rb'))
  File "/usr/local/lib/python2.7/dist-packages/telepot/__init__.py", line 234, in sendAudio
    return self._sendFile(audio, 'audio', p)
  File "/usr/local/lib/python2.7/dist-packages/telepot/__init__.py", line 226, in _sendFile
    return self._parse(r)
  File "/usr/local/lib/python2.7/dist-packages/telepot/__init__.py", line 177, in _parse
    raise TelegramError(data['description'], data['error_code'])
telepot.TelegramError: (u'[Error]: AUDIO_EXT_INVALID', 400)

It is possible to include this issue in the project?

Exception after a while

After a while I receive an exception

Traceback (most recent call last):
File "build/bdist.linux-i686/egg/telepot/init.py", line 427, in run
result = get_updates(offset=offset, timeout=self.timeout)
File "build/bdist.linux-i686/egg/telepot/init.py", line 374, in get_updates
return self.getUpdates(offset=offset, timeout=timeout)
File "build/bdist.linux-i686/egg/telepot/init.py", line 331, in getUpdates
r = requests.post(self._methodurl('getUpdates'), params=self._rectify(p), timeout=self._http_timeout+(0 if timeout is None else timeout))
File "/usr/local/lib/python2.7/site-packages/requests-2.8.1-py2.7.egg/requests/api.py", line 109, in post
return request('post', url, data=data, json=json, *_kwargs)
File "/usr/local/lib/python2.7/site-packages/requests-2.8.1-py2.7.egg/requests/api.py", line 50, in request
response = session.request(method=method, url=url, *_kwargs)
File "/usr/local/lib/python2.7/site-packages/requests-2.8.1-py2.7.egg/requests/sessions.py", line 468, in request
resp = self.send(prep, *_send_kwargs)
File "/usr/local/lib/python2.7/site-packages/requests-2.8.1-py2.7.egg/requests/sessions.py", line 576, in send
r = adapter.send(request, *_kwargs)
File "/usr/local/lib/python2.7/site-packages/requests-2.8.1-py2.7.egg/requests/adapters.py", line 435, in send
raise ReadTimeout(e, request=request)
ReadTimeout: HTTPSConnectionPool(host='api.telegram.org', port=443): Read timed out. (read timeout=50)

Is there a way to solve the problem?

No obvious way to access delegate once started

Once a delegate is spawned, I cannot see an obvious way to get information about the delegate. For example, I have a simple Pomodoro chat bot which starts a timer for 20 seconds, and I want to query how much time is left. But since the delegate is not the original class, self._current_pomodoro_handler is not the correct one (in fact, it's the initial value of None).

Is there a way to do this? If so, documentation would be good. If not, why not? (e.g. shouldn't be using DelegatorBot?) or could this be implemented?

class PomodoroHandler(telepot.helper.ChatHandler):
    def __init__(self, seed_tuple, timeout):
        super(PomodoroHandler, self).__init__(seed_tuple, timeout)
        self._bot._current_pomodoro_handler = None

    @asyncio.coroutine
    def on_message(self, msg):
        if "/pomodorostart" in msg["text"]:
            yield from self.pomodoro_begin(msg)
        if "/timeleft" in msg["text"]:
            yield from self.pomodoro_time_left(msg)

    @asyncio.coroutine
    def pomodoro_time_left(self, msg):
        # PROBLEM HERE (self._current_pomodoro_handler still at initial value)
        yield from self.sender.sendMessage(str(self._current_pomodoro_handler._when)) 

    @asyncio.coroutine
    def pomodoro_end(self, msg):
        yield from self.sender.sendMessage("POMODORO END!")

    @asyncio.coroutine
    def pomodoro_begin(self, msg):
        h = asyncio.get_event_loop().call_later(
            20,
            lambda: asyncio.async(self.pomodoro_end(msg)))
        self._current_pomodoro_handler = h

        yield from self.sender.sendMessage("POMODORO BEGIN!")

if __name__ == "__main__":
    bot = telepot.async.DelegatorBot(
        TELEGRAM_ID,
        [
            (per_chat_id(), create_open(
                PomodoroHandler, timeout=72*3600)),
        ])

    loop = asyncio.get_event_loop()
    loop.create_task(bot.messageLoop())
    loop.run_forever()

Async example doubles all the messages

When running the code below I get double the messages for every message I send:
Normal Message: text private 888888888
Normal Message: text private 888888888

What am I doing wrong?

import sys
import asyncio
import telepot
import telepot.async

def on_chat_message(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    print('Normal Message:', content_type, chat_type, chat_id)

def on_inline_query(msg):
    query_id, from_id, query_string = telepot.glance(msg, flavor='inline_query')
    print('Inline Query:', query_id, from_id, query_string)

    def compute_answer():
        articles = [{'type': 'article',
                        'id': 'abc', 'title': query_string, 'message_text': query_string}]

        return articles

    answerer.answer(msg, compute_answer)

def on_chosen_inline_result(msg):
    result_id, from_id, query_string = telepot.glance(msg, flavor='chosen_inline_result')
    print('Chosen Inline Result:', result_id, from_id, query_string)


TOKEN = sys.argv[1]  # get token from command-line

bot = telepot.async.Bot(TOKEN)
answerer = telepot.async.helper.Answerer(bot)

loop = asyncio.get_event_loop()
loop.create_task(bot.messageLoop({'normal': on_chat_message,
                                  'inline_query': on_inline_query,
                                  'chosen_inline_result': on_chosen_inline_result}))
print('Listening ...')

loop.run_forever()

'Photo has unsupported extension' when sending binary data as photo

I am trying to resend recieved document as photo. Document is an image sended without compression.

file = msg['document']['file_id']
file_path = bot.getFile(file)['file_path']
file_link = 'https://api.telegram.org/file/bot' + TOKEN + '/' + file_path
image = requests.get(file_link).content
bot.sendPhoto(msg['from'], image)

At last line I recieve

telepot.exception.TelegramError: ('[Error]: Photo has unsupported extension. Use one of .jpg, .jpeg, .gif, .png, .tif or .bmp', 400)

Constants for reply markups, content_type and chat_type

Hi! Thank you for a great lib! Did you think about add constants to the library?
Like telepot.content_type.TEXT or tepepot.ReplyKeyboardMarkup. I read about telepot.namedtuple but I'm talking about code completion on editors and easiest supporting of code if API will be changed. What do you think about it? If you want, I can help with it.

Error download video - file is too big

Hi
Why files are uploaded in messenger but not downloaded in telepot ?
Limit in telegrams above 1.5G?

`
{u'duration': 0, u'width': 0, u'file_size': 89704028, u'file_id': u'BAADAgADGwADIiE6********', u'height': 0}

Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/telepot/init.py", line 338, in handle
callback(update['message'])
File "/usr/local/lib/python2.7/dist-packages/telepot/helper.py", line 293, in route
fn(msg, *args)
File "./bot.py", line 27, in on_chat_message
bot.downloadFile(video_id, '/home/rustam/bot/'+video_id+'.mp4')
File "/usr/local/lib/python2.7/dist-packages/telepot/init.py", line 300, in downloadFile
f = self.getFile(file_id)
File "/usr/local/lib/python2.7/dist-packages/telepot/init.py", line 274, in getFile
return self._parse(r)
File "/usr/local/lib/python2.7/dist-packages/telepot/init.py", line 179, in _parse
raise TelegramError(description, error_code, data)
TelegramError: (u'[Error]: Bad Request: file is too big[size:89704028]', 400, {u'error_code': 400, u'ok': False, u'description': u'[
Error]: Bad Request: file is too big[size:89704028]'})
`

Inline Query

Hey there,
first of all, great work you did there, thanks for the API!
I've been trying to send messages to the bot using inline query, with your API but had to find out it doesn't seem to be supported. Here's what i get when receiving an inline query with notifyOnMessage:

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/telepot/__init__.py", line 379, in handle
    callback(update['message'])
KeyError: 'message'

This is what i'm trying right now:

import time
import pprint
import telepot
from pprint import pprint
bot = telepot.Bot('MY_KEY')

def handle(msg):
       messageObject = msg
       pprint(messageObject)  # to test if it sends me any kind of object.
       if messageObject['chat']['type'] == 'group':    # making sure it is a group
               chat_id = messageObject['chat']['id']    # putting needed info in vars for easier usage
               name = messageObject['chat']['username']
               message = messageObject['text']
               print(chat_id)    # just some prints to check what the program is receiving
               print(name)
               print(message)

               bot.sendMessage(chat_id, 'Hello @' + name + ', ' + message)    # send a msg to the Chat



bot.notifyOnMessage(handle)
print 'Listening ...'
# Keep the program running.
while 1:
    time.sleep(10)


It actually works when sending the complete message, but i wanna work with inline queries.^^
I'm pretty new to python so please bear with me if i'm just being stupid or something.
Is there any way i can deal with this issue?

Location support

I've heard that Telegram Bots 2.0 now support location asking support.

Will be this feature implemented in telepot?

Thank you!

Unable to add bot in supergroup

Inline answer don't show up

I am running InlineQueryResult sample but with InlineQueryResultPhoto instead of article as shown elow:

articles = [InlineQueryResultPhoto(id='123', 
    photo_url='http://www.html5rocks.com/en/tutorials/speed/img-compression/len_std.jpg',
    thumb_url='http://www.html5rocks.com/en/tutorials/speed/img-compression/len_std.jpg')
]

I've had import InlineQueryResultPhoto from telepot.namedtuple with:

from telepot.namedtuple import *

But when I test it on Telegram Desktop or mobile versions, I can't see the query answers.
err-and
Desktop view.

err-desk
On Android version.

Console show this error after timeout is finish:

$ python inline_sample.py <token>
(49873, ':', 'Inline Query:', u'214204250116192', 49873, u'')
ERROR:root:on_close() called due to WaitTooLong:

Image is:
photo-test

Any idea how can I solved my problem.

`new_chat_participant` vs `new_chat_member`

Hello,
while reading the bot api v2 changes i noticed they changed new_chat_participant to new_chat_member. right now api sends both these keys:

{'chat': {'id': -141713840, 'title': 'ASCII', 'type': 'group'},
 'date': 1460909329,
 'from': {'first_name': 'Bor',
          'id': 614*****,
          'last_name': '691',
          'username': '******'},
 'message_id': 1420,
 'new_chat_member': {'first_name': 'b_devbot',
                     'id': 190782732,
                     'username': 'b_devbot'},
 'new_chat_participant': {'first_name': 'b_devbot',
                          'id': 190782732,
                          'username': 'b_devbot'}}

right now telepot glance returns new_chat_participant as content_type. what are your plans when updating telepot , will you change glance to return new_chat_member instead?
that would break compatibility with old code , yet not changing it will break scripts in the future when they remove the duplicates eventually.

Missing `forward_from` in forwarded messages from channels

Hello,
this is a typical update for a forwarded message (e.g. forwarded from a user to the bot):

{
    "update_id": 777882727,
    "message": {
        "message_id": 808,
        "from": {
            "id": 12312312,
            "first_name": "Bor",
            "last_name": "691",
            "username": "------"
        },
        "chat": {
            "id": 12312312,
            "first_name": "Bor",
            "last_name": "691",
            "username": "------",
            "type": "private"
        },
        "date": 1458924324,
        "forward_from": {
            "id": 32132132,
            "first_name": "his name",
            "last_name": "his lastname",
            "username": "------"
        },
        "forward_date": 1458826816,
        "text": "zarar ke nadare"
    }
}

as you can see a User object with key forwarded_from is present which informs that message was forwarded. however when a message is forwarded from a channel to the bot :

image

note: content type of message is irrelevant , a simple text message is also missing the forward_from

as you can see the forward_from key is missing , as a result there is no way to tell if user has sent the message himself or it's forwarded from a channel , yet if the bot forwards the message it would appear from channel not the user.

i know there is not much that can be done at telepot to fix it , however i have tried contacting telegram support , telegram bot support ( @botsupport ) and all the other ways i knew of.

due nature of my bot this is crucial for me to be able to tell the difference between a normal message and a forwarded one , so question is , can you think of any workarounds or if not , how should i proceed to submit a bug report to the telegram bot api ?

also as a side question , am i correct to assume this is a bug ? or is it working as intended ?

bot.anwserInlineQuery doesn't work.

Hi,
The bot.answerInlineQuery(query_id, InlineQueryResultArtice( ... -example doesn't lead to any reaction on the telegram chat client. The API doesn't produce an error, though.

BadHTTPResponse 502

Been running the bot for a long time now, and today the bot stopped answering.
I have not modified the code in while. All I get is the error message below when the boot tries to pull new messages. I have testet on 2 diffrents servers and made sure im running the latest version of telepot. Any help?

Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/telepot/__init__.py", line 348, in get_from_telegram_server result = self.getUpdates(offset=offset, timeout=timeout) File "/usr/local/lib/python2.7/dist-packages/telepot/__init__.py", line 273, in getUpdates return self._parse(r) File "/usr/local/lib/python2.7/dist-packages/telepot/__init__.py", line 166, in _parse raise BadHTTPResponse(response.status_code, response.text) BadHTTPResponse: (502, u'<html>\r\n<head><title>502 Bad Gateway</title></head>\r\n<body bgcolor="white">\r\n<center><h1>502 Bad Gateway</h1></center>\r\n<hr><center>nginx/1.6.2</center>\r\n</body>\r\n</html>\r\n')

Display appropriate error message on invalid token

Hello, me again :)

so this took me a while to figure out , if you supply an invalid token , say asd , telegram redirects you to https://core.telegram.org/bots .
to try click on this link : http://api.telegram.org/botasd/getMe

this results in a BadHTTPResponse with a 27KB unreadable html in the console...
i know that its my job to validate the tokens before passing it to telepot , but on this last project on which the tokens where provided by users, it took me a while to figure out what was going on , perhaps you could raise a TelegramError with message invalid token instead of 27KB of html?

example code :

import telepot

bot = telepot.Bot('asd')
bot.getMe()

results in :
image

html actually fills the cmd buffer , so the actual error is not even visible , i had to dump the output to a file to find out what's what.

thanks in advance.

Can't post photo without a photo file buffer

I'm reading a file directly from a web source, so I've got its data as bytes.
Using io.BytesIO I can get the buffer for it, but attempting to post the photo will give me an error:

telepot.TelegramError: ('[Error]: Photo has unsupported extension. Use one of .jpg, .jpeg, .gif, .png, .tif or .bmp', 400)

This is how I was attempting it:

bot.sendPhoto( chat, BytesIO(urlopen( imageURL ).read()) )

So I tried to use a cache file to store the data. You'll have to take my word for it, but the file was properly stored and I was able to open it:

    with open( 'cache' , 'wb') as f:
        f.write( urlopen( imageURL ).read() )
    bot.sendPhoto( chat, open( 'cache', 'rb' ) )

This gave me the exact same error.
However, appending '.jpg' to the end of the cached file name worked and the image was properly posted in the chat.

So my question is 'How do I post a photo without caching the data in a file with an image extension?'

Async support will start at Python 3.5.1

To all Async Version Users

I am going to stop supporting Python 3.4 on around May 31th, 2016. Async support will start at Python 3.5.1. Keyword async and await will be used. Main reason for the change is that it is much easier to ensure closing of connection using async with, which is not available in Python 3.4. Let's all move with the times, and not get bogged down by the past.

Currently, telepot's async version already works with Python 3.5.1.

This announcement only concerns telepot's async version. Traditional version is not affected.

After a certain period of time it did not receive the message

sorry, i'm use google translate.

please understand

i'm use telepot from xpenology system.

bot = telepot.DelegatorBot(TOKEN, [
(per_from_id(), create_open(BotManager.BOTManager, timeout=120)),
])

class BOTManager(telepot.helper.UserHandler):
def init(self, seed_tuple, timeout):
super(BOTManager, self).init(seed_tuple, timeout)

def on_message(self, msg):
Message Processing Code...

def on_close(self, exception):
on_close log write...

def close(code=None, reason=None):
close log write

After the message was sent three hours after the teapot receive messages all

my source code is here
https://github.com/acidpop/xpebot

thank you~!

adding some kind of message routing

Hello,
this is mostly a feature request , but before we add it to telepot we should discuss to see what would be the best way to add it.

so i saw this library today https://github.com/eternnoir/pyTelegramBotAPI .
while i prefer telepot there are some nice ideas implanted there. like the following :

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

you can specify commands , content_types, a regex or a lambda to determine which handler to be called. i don't specifically like the decorator syntax , but i feel something similar is missing from telegram.

i was thinking maybe we can subclass delegator bot to make an alternative class based handling , where instead of only dividing by message flavor we can have on_audio_message kind of functions , the new class should check availability of on_{content_type}_message method , if it was not present useon_chat_message or if that wasn't present either on_message would get the message.

furthermore we can add a routing scheme for commands , with a naming convention . i would propose something like cmd_start , where if message content type was text , and text started with /start availability of cmd_X would be checked before other methods described above.

a class constant could be used to define an array of command starters for them to be customizable.
e.g.:

class MyBot(RouterBot):
    command_indicators = ['!','#','/']

with this class cmd_start would be callable by /start , !start and #start.
also it would be nice if we could override methods used for routing to add functionality and keep telepot extensible.

as for regex or lambda based routing , we can either have a new naming convention like handler_X which should return a tuple of (condition, callback) or some way of registering methods to the routing system. for example in the init of class.

class MyBot(RouterBot):
    def __init__(self):
        self.routes.append(condition, self.handler)

where condition would either be a regex (would be checked against text of message if available) or a lambda. or we can use decorators .

what is your opinion on this?
btw sorry for the long issue, i tried to write it briefly.

TelegramError: (u'[Error]: Conflict: terminated by other long poll or webhook', 409)

I've created a shell script that starts on login on raspberry pi, this script listen for a telegram bot command /photo. I noticed that script stops and command has not response. Occours this error TelegramError: (u'[Error]: Conflict: terminated by other long poll or webhook', 409). Does anyone have experienced this issue? Thanks in advance.

Receiving same message twice

import time

import telepot


def handler(msg):
    content_type, chat_type, chat_id = telepot.glance2(msg)
    bot.sendMessage(chat_id, msg['text'])


bot = telepot.Bot('token')
bot.notifyOnMessage(handler)

while 1:
    time.sleep(15)

I get calling handler function twice on sending one message to bot.

I made some investigation and found that telepot function getUpdates(offset=offset, timeout=timeout) return result with two equal messages from telegram server.
Maybe i do something wrong?

Can't detect a invalid Token.

I'm are creating a script that permits the user select his token.
When i do it:

    try:
        bot.notifyOnMessage(handle)
    except:
        error_msg('Invalid token.')

I receive this giant error:

Traceback (most recent call last):
  File "C:\Python34\lib\site-packages\telepot\__init__.py", line 237, in _parse
    data = response.json()
  File "C:\Python34\lib\site-packages\requests\models.py", line 805, in json
    return complexjson.loads(self.text, **kwargs)
  File "C:\Python34\lib\json\__init__.py", line 318, in loads
    return _default_decoder.decode(s)
  File "C:\Python34\lib\json\decoder.py", line 343, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Python34\lib\json\decoder.py", line 361, in raw_decode
    raise ValueError(errmsg("Expecting value", s, err.value)) from None
ValueError: Expecting value: line 1 column 1 (char 0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python34\lib\site-packages\telepot\__init__.py", line 427, in run
    result = get_updates(offset=offset, timeout=self.timeout)
  File "C:\Python34\lib\site-packages\telepot\__init__.py", line 374, in get_updates
    return self.getUpdates(offset=offset, timeout=timeout)
  File "C:\Python34\lib\site-packages\telepot\__init__.py", line 332, in getUpdates
    return self._parse(r)
  File "C:\Python34\lib\site-packages\telepot\__init__.py", line 239, in _parse
    raise BadHTTPResponse(response.status_code, response.text)
telepot.BadHTTPResponse: (200, 'telegram\'s default api docs page here')```

How i solve it?

How to pass parse_mode

Is there a way to pass parse_mode via the sendMessage command? I want to send a message with links in it and need to set the parse_mode to markdown.

help for a dummy...

well .. i have no idea on how to send you a msg.. or where ask for help about your project...
so sorry if i made something wrong .. writing this msg as issue!!!!

well.. i dont know anything about python... but i know something of php.. mysql.. and visual basic..
so.. i try to understand as best as i can...

well.. right now .. im not stil able to ANSWER...
for example :
/start

  • please select a feature from A , B, C
    ... at this point i cant grab the answer... and i cannot find a tutorial on how TO DO THAT...

i tried to do something like that.. but i (obviously) FAILED...
this is the "amazing" code i tried....
(bad code deleted)
works well till it ask me "dammi un comando".. then when i write "sposta"...
it answers me "Scusa.. mi aspetto un pin numerico..."... That's so sad!!
please help me to understand how to manage this answers!!!!

Can't whitelist some users to use the Bot

As far as I've seen, if you want to use the bot for personal reasons (for example, domotic projects), you can't have a whitelist of users you want to allow talking to the Bot.

Is there any way to do it? I've seen that here have implemented something similar.

I would like to know how to perform it even if now this functionality is not implemented yet.

Thank you!

Unable to send message in parse mode

I'm trying to send message in parse mode using this function

bot.sendMessage(chat_id, parse_mode='*text*')

And after i got this

TypeError: sendMessage() takes at least 3 arguments (3 given)

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.