-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathbot.py
60 lines (45 loc) · 1.84 KB
/
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
import requests
import time
import json
import os
from dotenv import load_dotenv
load_dotenv()
BOT_ID = os.getenv("BOT_ID")
GROUP_ID = os.getenv("GROUP_ID")
ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
LAST_MESSAGE_ID = None
def send_message(text, attachments=None):
"""Send a message to the group using the bot."""
post_url = "https://api.groupme.com/v3/bots/post"
data = {"bot_id": BOT_ID, "text": text, "attachments": attachments or []}
response = requests.post(post_url, json=data)
return response.status_code == 202
def get_group_messages(since_id=None):
"""Retrieve recent messages from the group."""
params = {"token": ACCESS_TOKEN}
if since_id:
params["since_id"] = since_id
get_url = f"https://api.groupme.com/v3/groups/{GROUP_ID}/messages"
response = requests.get(get_url, params=params)
if response.status_code == 200:
# this shows how to use the .get() method to get specifically the messages but there is more you can do (hint: sample.json)
return response.json().get("response", {}).get("messages", [])
return []
def process_message(message):
"""Process and respond to a message."""
global LAST_MESSAGE_ID
text = message["text"].lower()
# i.e. responding to a specific message (note that this checks if "hello bot" is anywhere in the message, not just the beginning)
if "hello bot" in text:
send_message("sup")
LAST_MESSAGE_ID = message["id"]
def main():
global LAST_MESSAGE_ID
# this is an infinite loop that will try to read (potentially) new messages every 10 seconds, but you can change this to run only once or whatever you want
while True:
messages = get_group_messages(LAST_MESSAGE_ID)
for message in reversed(messages):
process_message(message)
time.sleep(10)
if __name__ == "__main__":
main()