TelegramBot - HomeMadePy/messages GitHub Wiki

The telegram module provides an easy and intuitive interface to construct and send messages via the Telegram Bot API.

TelegramBot API

TelegramBot(**from_**=None, auth=None, chat_id=None, to=None, subject=None, body="", attachments=None, params=None,verbose=False)

  • from_: (str) [optional] arg to specify who message is from.
  • auth: (str) auth token for bot. May use environment variables to pull auth credentials or whatever means you feel necessary.
  • chat_id: (str) chat_id for already-intiated chat. Integer represented as a string. Recipient must have already initiated chat at some point in the past for bot to send message.
  • to: (str) [optional] if chat_id is unknown, can specify username of recipient to lookup via API call. This may return None if chat is older than 24-hours old.
  • subject: (str) [optional] arg to specify message subject.
  • body: (str) [optional] message to send.
  • attachments: [optional] (str or list) each item is a url to attach
  • params: (dict) [optional] additional attributes to add to message, i.e. parse_mode (HTML or Markdown, see API for information on which attributes are possible.
  • verbose: (bool) [optional] print verbose output.

Usage

After instantiating a TelegramBot object, using the API above, the following method can be used to send the message:

  • send(): sends the message synchronously

Example

Script/REPL

>>> from messages import TelegramBot
>>> msg = 'Hello,\n\tTry this new package called MESSAGES!'
>>> t = TelegramBot(
            auth='1234:ABCDEF',
            chat_id='12345678',
            body=msg,
            attachments=['https://url1.com/picture.gif', 'https://url2.com/file.pdf'],
        )
>>>
>>> t.send()       
Message sent...

Telegram API

  • See the Telegram API documentation for more information
  • You must create a Telegram Bot first in order to use this feature
  • In order to send messages, a chat must have already been initiated between the bot and the intended recipient (otherwise bots would be spamming everyone on Telegram). Therefore, use the App first to initiate a chat, then the python package will work with that specific user.
  • To find the chat_id param, initiate a chat via a standard telegram client with the bot account, then you can use the get_chat_id method:
>>> from messages import TelegramBot
>>> t = TelegramBot(auth='ABCD:1234')    
>>> t.get_chat_id('@yourUserName')
1234567

TODO

  • At the moment only urls can be uploaded as files, specifically only .jpg, .gif, and .pdf files. Need to enable file uploads from local host to send to the Telegram client. Help wanted.