Skip to content

Bot

Package containing the TelegramBot core class.

InputError

Base class for input exception.

TelegramBot

This class allows to send through a Telegram Bot text, images and plots. Furthermore the send messages can be updated.

__init__(self, token=None, user_ids=None, cred_file=None, tmp_dir='./temp/') special

Constructor

Warning

At least one between (token, user_ids) and cred_file has to be passed.

Parameters:

Name Type Description Default
token str

Telegram token

None
user_ids Union[int, list]

Telegram chat id to which send the messages

None
cred_file Union[str, dict]

Path to or the dict containing the token and the user_ids.

{
    "token": "<your_token>",
    "user_ids": <user_id>
}
None
tmp_dir

Folder in which store the temporary images. The folder will be created if not existing.

'./temp/'
Source code in bob_telegram_tools\bot.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def __init__(self, token: str = None, user_ids: Union[int, list] = None, cred_file: Union[str, dict] = None, tmp_dir='./temp/'):
    """
    Constructor

    !!! warning 
        At least one between (token, user_ids) and cred_file has to be passed. 

    Arguments:
        token : Telegram token

        user_ids : Telegram chat id to which send the messages

        cred_file : Path to or the dict containing the token and the user_ids.
            ```json
            {
                "token": "<your_token>",
                "user_ids": <user_id>
            }
            ```

        tmp_dir : Folder in which store the temporary images. The folder will be created if not existing.
    """
    if user_ids == cred_file == user_ids:
        raise InputError(
            'At least one between (token, user_ids) and cred_file has to be passed.')

    if cred_file is not None:
        with open(cred_file) as json_file:
            data = json.load(json_file)
            token = data['token']
            user_ids = data['user_ids']

    self.bot = telegram.Bot(token)
    self.user_ids = user_ids
    self.tmp_dir = tmp_dir

clean_tmp_dir(self)

Delete temporary folder function.

Source code in bob_telegram_tools\bot.py
174
175
176
177
178
def clean_tmp_dir(self):
    """
    Delete temporary folder function.
    """
    shutil.rmtree(self.tmp_dir)

send_image(self, img_path)

Send plot function. Returns the message obj needed for the update method.

Parameters:

Name Type Description Default
img_path str

Path of the image file to send

required

Returns:

Type Description
Message

Message Object

Source code in bob_telegram_tools\bot.py
134
135
136
137
138
139
140
141
142
143
144
145
def send_image(self, img_path: str) -> telegram.Message:
    """
    Send plot function. Returns the message obj needed for the update method.

    Arguments:
        img_path : Path of the image file to send

    Returns:
        Message Object 

    """
    return self.bot.send_photo(self.user_ids, open(img_path, 'rb'))

send_plot(self, plt, name=None)

Send plot function. Returns the message obj needed for the update method.

Parameters:

Name Type Description Default
plt

Plot to send

required
name str

Name of the temporary file

None

Returns:

Type Description
Message

Message Object

Source code in bob_telegram_tools\bot.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
def send_plot(self, plt, name: str = None) -> telegram.Message:
    """
    Send plot function. Returns the message obj needed for the update method.

    Arguments:
        plt : Plot to send

        name : Name of the temporary file

    Returns:
        Message Object 

    """
    if not os.path.exists(self.tmp_dir):
        os.makedirs(self.tmp_dir)

    if name is None:
        ts = int(time.time())
        img_path = self.tmp_dir+str(ts)+'.png'
    else:
        img_path = self.tmp_dir+name

    plt.savefig(img_path, dpi=100)
    return self.bot.send_photo(self.user_ids, open(img_path, 'rb'))

send_text(self, text)

Send text function. Returns the message obj needed for the update method.

Parameters:

Name Type Description Default
text str

Text to send

required

Returns:

Type Description
Message

Message Object

Source code in bob_telegram_tools\bot.py
63
64
65
66
67
68
69
70
71
72
73
74
def send_text(self, text: str) ->telegram.Message:
    """
    Send text function. Returns the message obj needed for the update method.

    Arguments:
        text : Text to send

    Returns:
        Message Object 

    """
    return self.bot.send_message(self.user_ids, text)

update_plot(self, message, plt, name=None)

Update plot function.

Parameters:

Name Type Description Default
message Message

Message to update

required
plt

New plot to send

required
name str

Name of the temporary file

None
Source code in bob_telegram_tools\bot.py
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
def update_plot(self, message: telegram.Message, plt, name: str = None):
    """
    Update plot function.

    Arguments:
        message : Message to update

        plt : New plot to send

        name : Name of the temporary file
    """
    if not os.path.exists(self.tmp_dir):
        os.makedirs(self.tmp_dir)

    if name is None:
        ts = int(time.time())
        img_path = self.tmp_dir+str(ts)+'.png'
    else:
        img_path = self.tmp_dir+name

    plt.savefig(img_path, dpi=100)
    new_media = telegram.InputMediaPhoto(open(img_path, 'rb'))
    try:
        message.edit_media(new_media)
    except Exception as e:
        pass

update_text(self, message, text)

Update text function.

Parameters:

Name Type Description Default
message Message

Message to update

required
text str

New text to send

required
Source code in bob_telegram_tools\bot.py
76
77
78
79
80
81
82
83
84
85
86
87
88
89
def update_text(self, message: telegram.Message, text: str):
    """
    Update text function.

    Arguments:
        message : Message to update

        text : New text to send
    """
    if message.text != text:
        try:
            message.edit_text(text)
        except Exception as e:
            pass