aboutsummaryrefslogtreecommitdiffstats
path: root/project/telegramapicommunicator.py
blob: 7fdb29c402a750aff909ed0d86cb79039b408a51 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import logging
import sys

import telepot

from project.basecommunicator import BaseCommunicator


class TelegramCommunicator(BaseCommunicator):
    """Class for communicating with the Telegram API"""

    chat_id = "default_id"
    bot = None
    token = "DEFAULT_TOKEN_123"

    @staticmethod
    def spawn_bot(token):
        TelegramCommunicator.bot = telepot.Bot(token)

    @staticmethod
    def fetch():
        raise Exception("""Attempted to fetch messages from Telegram manually.
                        Please use telepot bot functionality for listening to messages.""")

    @staticmethod
    def send(data):
        TelegramCommunicator.send_raw("{}: {}".format(data["user"], data["text"]))

    @staticmethod
    def send_raw(message):
        try:
            TelegramCommunicator.bot.sendMessage(TelegramCommunicator.chat_id,
                                                 message)
        except:
            logging.warning("Could not send message to Telegram chat id {}!".format(TelegramCommunicator.chat_id))

    @staticmethod
    def start_listening(handle):
        try:
            logging.info("Bot info: {}".format(TelegramCommunicator.bot.getMe()))
        except:
            logging.error("Could not fetch bot info. Check your token and connectivity to Telegram!")
            sys.exit(1)

        TelegramCommunicator.bot.message_loop(handle)

        logging.info("Listening for messages...")