tfb-groupme-bridge/tfbbridge/bridge/groupme.py

135 lines
3.2 KiB
Python
Raw Permalink Normal View History

2025-01-02 17:49:01 -06:00
from dataclasses import dataclass
from typing import ClassVar, Any, Optional
from urllib.parse import urlencode
import requests
import json
@dataclass
class GMUser:
name: str
userid: str
x_role: Optional[str] = None # always "trusted"
x_messages: Optional[int] = 0
def __eq__(self, other):
if isinstance(other, GMUser):
return self.userid == other.userid
else:
raise NotImplementedError("Comparison with non-GMUser objects not allowed")
def __hash__(self):
return self.userid
@property
def sortkey(self):
return name
@dataclass
class GMChannel:
name: str
chanid: str
admins: list[GMUser]
members: list[GMUser]
x_role: Optional[str] = None # either "following" or "trusted"
@dataclass
class GMBot:
name: str
chanid: str
callback: Optional[str] = None
chankey: Optional[str] = None
@dataclass
class GroupMe:
prefix: ClassVar[str] = "https://api.groupme.com/v3"
token: str
def _construct_url(self, endpoint: str, params: dict[str,str] = {}) -> str:
params["token"] = self.token
return "{}/{}?{}".format(self.prefix, endpoint, urlencode(params))
_cons_url: ClassVar[Any] = _construct_url
def me(self):
r = requests.get(
self._cons_url("users/me")
)
data = r.json()["response"]
return GMUser(data["name"], data["id"])
def groups(self):
r = requests.get(
self._cons_url("groups", { "per_page": 200 }),
)
data = r.json()["response"]
output = []
for group in data:
members = []
admins = []
for member in group["members"]:
new_member = GMUser(member["name"], member["user_id"])
if "admin" in member["roles"]:
admins.append(new_member)
members.append(new_member)
output.append(GMChannel(
group["name"],
group["group_id"],
admins,
members
))
return output
def register_bot(self, bot: GMBot):
data = {
"bot": {
"name": bot.name,
"group_id": bot.chanid,
"active": True,
}
}
if bot.callback:
data["bot"]["callback_url"] = bot.callback
r = requests.post(
self._cons_url("bots"),
data=json.dumps(data),
headers={"Content-Type": "application/json"},
)
data = r.json()["response"]["bot"]
name = data["name"]
chanid = data["group_id"]
chankey = data["bot_id"]
callback = data["callback_url"]
return GMBot(name, chanid, callback, chankey)
if __name__ == "__main__":
api = GroupMe(input("token? "))
me = api.me()
groups = api.groups()
for group in groups:
if me in group.admins:
name = group.name
if name == "another group":
bot = GMBot(
"tfbbot",
group.chanid,
"https://marching.beepboop.systems",
)
bot = api.register_bot(bot)
print(bot)
break