This repository has been archived by the owner on Feb 22, 2022. It is now read-only.
forked from jerbob/groupme-discord
-
Notifications
You must be signed in to change notification settings - Fork 1
/
discord_bot.py
100 lines (80 loc) · 3.14 KB
/
discord_bot.py
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
88
89
90
91
92
93
94
95
96
97
98
99
100
"""Discord-side message parsing and posting to GroupMe."""
import json
from os import path
from sys import exit
from io import BytesIO
from random import randint
from multiprocessing import Process
from typing import List, Union, Optional, Callable
from discord.ext import commands
from aiohttp import ClientSession
from discord import Attachment, Message
async def post(
session: ClientSession, url: str,
payload: Union[BytesIO, dict], headers: Optional[dict] = None
) -> str:
"""Post data to a specified url."""
async with session.post(url, data=payload) as response:
return await response.text()
def get_prefix(
bot_instance: commands.Bot, message: Message
) -> Callable[[commands.Bot, Message], list]:
"""Decide prefixes of the Bot."""
prefixes = ['chat!', '>']
return commands.when_mentioned_or(*prefixes)(bot_instance, message)
bot = commands.Bot(command_prefix=get_prefix)
endpoint = 'https://api.groupme.com/v3/bots/post'
sent_buffer = [] # Buffer for webhook message deletions.
async def send_message(message: Message) -> str:
"""Send a message to the group chat."""
text = f'{message.author.display_name}: {message.content}'.strip()
sent_buffer.append(text)
if len(sent_buffer) > 10:
sent_buffer.pop(0)
payload = {
'bot_id': GROUPME_ID,
'text': f'{message.author.display_name}: {message.content}'
}
cdn = await process_attachments(message.attachments)
if cdn is not None:
payload.update({'picture_url': cdn})
async with ClientSession() as session:
return await post(session, endpoint, payload)
async def process_attachments(attachments: List[Attachment]) -> str:
"""Process the attachments of a message and return GroupMe objects."""
if not attachments:
return
attachment = attachments[0]
url = 'https://image.groupme.com/pictures'
if not attachment.filename.endswith(('jpeg', 'jpg', 'png', 'gif')):
return
extension = attachment.filename.partition('.')[-1]
if extension == 'jpg':
extension = 'jpeg'
handler = BytesIO()
await attachment.save(handler)
headers = {
'X-Access-Token': GROUPME_TOKEN,
'Content-Type': f'image/{extension}'
}
async with ClientSession(headers=headers) as session:
cdn = await post(session, url, handler.read())
cdn = json.loads(cdn)['payload']['url']
return cdn
@bot.event
async def on_ready() -> None:
"""Called when the bot loads."""
print('-------------\nBot is ready!\n-------------')
@bot.event
async def on_message(message: Message) -> None:
"""Called on each message sent in a channel."""
if CHANNEL_NAME in str(message.channel):
if not message.author.bot:
print(await send_message(message))
elif message.content in sent_buffer:
await message.delete()
def main(botToken, groupmeToken, groupmeID, channelName):
global BOT_TOKEN, GROUPME_TOKEN, GROUPME_ID, CHANNEL_NAME
BOT_TOKEN, GROUPME_TOKEN, GROUPME_ID, CHANNEL_NAME = botToken,groupmeToken,groupmeID,channelName
"""Start the bot with the provided token."""
Process(target=bot.run, args=(BOT_TOKEN,)).start()