Skip to content

Commit

Permalink
Initial support for server nicknames in Discord
Browse files Browse the repository at this point in the history
  • Loading branch information
dummyx committed Jul 29, 2022
1 parent 31ec63f commit 783885c
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
18 changes: 18 additions & 0 deletions bygeon/messenger/definition/discord.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ class Endpoints:
DELETE_MESSAGE = "https://discordapp.com/api/channels/{}/messages/{}"
EDIT_MESSAGE = "https://discordapp.com/api/channels/{}/messages/{}"
GET_EMOJI = "https://cdn.discordapp.com/emojis/{}"
GET_CHANNEL = "https://discordapp.com/api/channels/{}"
LIST_GUILD_MEMBERS = "https://discordapp.com/api/guilds/{}/members"


class ReferencedMessage(TypedDict):
Expand Down Expand Up @@ -65,6 +67,22 @@ class Role(TypedDict):
pass


class GuildMember(TypedDict):
user: User
nick: NotRequired[Optional[str]]
avatar: Optional[str]
roles: List[str]
joined_at: str
premium_since: str
deaf: bool
mute: bool
pending: NotRequired[bool]
permissions: NotRequired[str]
communication_disabled_until: str

pass


class Attachment(TypedDict):
id: str
filename: str
Expand Down
25 changes: 24 additions & 1 deletion bygeon/messenger/discord.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
EventName,
WebsocketMessage,
Endpoints,
GuildMember,
)
from .definition.discord import (
MessageCreateEvent,
Expand All @@ -40,6 +41,7 @@ def __init__(self, bot_token: str, channel_id: str, hub: Hub) -> None:
self.sequence = None
self.session_id = None

self.nickname_dict = self.get_nicknames()
self.logger = self.get_logger()

@property
Expand Down Expand Up @@ -151,7 +153,7 @@ def handle_message_create(self, data: MessageCreateEvent) -> None:
self.logger.info("Received message: %s", text)

author = data["author"]
username = author["username"]
username = self.nickname_dict.get(author["id"], author["username"])
attachments: List[Attachment] = []
for attachment in data["attachments"]:
url = attachment["url"]
Expand Down Expand Up @@ -308,6 +310,27 @@ def reconnect(self) -> None:
self.start()
self.join()

def get_nicknames(self) -> Dict[str, str]:
r = requests.get(
Endpoints.GET_CHANNEL.format(self.channel_id), headers=self.headers
)

guild_id = r.json()["guild_id"]

r = requests.get(
Endpoints.LIST_GUILD_MEMBERS.format(guild_id), headers=self.headers
)
print(r.text)
nickname_dict: Dict[str, str] = {}
guild_members: List[GuildMember] = orjson.loads(r.text)

for member in guild_members:
if member.get("nick") is None:
continue
nickname_dict[member["user"]["id"]] = cast(str, member["nick"])
print(nickname_dict)
return nickname_dict

def start(self) -> None:
self.ws = WSApp(
Endpoints.GATEWAY,
Expand Down

0 comments on commit 783885c

Please sign in to comment.