-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbots.py
More file actions
88 lines (64 loc) · 2.13 KB
/
bots.py
File metadata and controls
88 lines (64 loc) · 2.13 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
"""
File: bots.py
Author: Leonardo Lucio Custode
Github: github.com/leocus
Description: This file contains an implementation of intefaces
for messaging platforms
"""
import abc
import slack
import asyncio
import telegram
class BotRegister:
bots = {}
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
cls.bots[cls.__name__] = cls
def make_bot(cls, kwargs):
return cls.bots[kwargs.bot.class_name](**kwargs.bot.parameters)
class Bot:
"""This is the base class for messaging bots."""
@abc.abstractmethod
def send_message(self, text: str):
"""
Sends a message to a pre-determined recipient.
:text: The text to be sent.
:returns: None
"""
pass
class TelegramBot(Bot, BotRegister):
"""A bot interface that interacts with the Telegram APIs."""
def __init__(self, token: str, chat_id: str):
"""
Initializes the bot.
:token: The bot's token returned by BotFather
:chat_id: The chat where to send the messages
"""
Bot.__init__(self)
self._token = token
self._chat_id = chat_id
self._bot = telegram.Bot(self._token)
def send_message(self, text: str):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
loop.run_until_complete(self._send_message_async(text))
finally:
loop.close()
async def _send_message_async(self, text: str):
async with self._bot:
await self._bot.send_message(text=text, chat_id=self._chat_id, parse_mode="HTML")
class SlackBot(Bot, BotRegister):
"""A bot interface that interacts with the Slack APIs."""
def __init__(self, token: str, channel: str):
"""
Initializes the bot.
:token: The bot's token
:chat_id: The chat where to send the messages
"""
Bot.__init__(self)
self._token = token
self._channel = channel
self._bot = slack.WebClient(token=token)
def send_message(self, text: str):
self._bot.chat_postMessage(channel=self._channel, text=text)