Skip to content

Commit

Permalink
Merge pull request #66 from nzlosh/master
Browse files Browse the repository at this point in the history
Fix user id lookup
  • Loading branch information
nzlosh authored Apr 22, 2024
2 parents da8e41d + 5fb1a38 commit 62e8bf0
Show file tree
Hide file tree
Showing 12 changed files with 61 additions and 83 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/python-package.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ jobs:
python-version: ["3.8", "3.9", "3.10", "3.11"]

steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}

Expand Down
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.

## [4.0.1] Unreleased

## [4.0.1] 2024-03-25

### Added

### Changed
Expand Down
1 change: 0 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,3 @@ Visit the [official documentation](https://err-backend-discord.readthedocs.io/)
- Configuration
- User Guide
- Developer Guide

5 changes: 4 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "err-backend-discord"
version = "4.0.0"
version = "4.0.1"
authors = [{ name="Errbot maintainers", email="[email protected]" }]
keywords = [
"errbot",
Expand Down Expand Up @@ -35,3 +35,6 @@ dependencies = [
[tool.setuptools]
# available as beta since setuptools version 61.0.0
include-package-data = true

[tool.black]
line-length = 100
20 changes: 11 additions & 9 deletions src/err-backend-discord/discordlib/person.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,17 +38,19 @@ def get_discord_object(self) -> discord.abc.Messageable:

class DiscordPerson(Person, DiscordSender):
@classmethod
def username_and_discriminator_to_userid(cls, username: str, discriminator: str) -> str:
return discord.utils.find(
lambda m: m.name == username and m.discriminator == discriminator,
DiscordPerson.client.get_all_members(),
)
def resolve_username(cls, username: str, discriminator: str) -> str:
for m in DiscordPerson.client.get_all_members():
if m.name == username:
# Discord dropped discriminators for user accounts but kept them for bot accounts.
if m.discriminator in ["0", discriminator]:
return m
return None

def __init__(self, user_id: str = None, username: str = None, discriminator: str = None):
def __init__(self, user_id: str = None, username: str = None, discriminator: str = "0"):
"""
@user_id: _must_ be a string representation of a Discord Snowflake (an integer).
@username: Discord username.
@discriminator: Discord discriminator to uniquely identify the username.
@discriminator: Discord discriminator to uniquely identify the username. (default to 0 since discord dropped them for username)
"""
if user_id:
if not re.match(RE_DISCORD_ID, str(user_id)):
Expand All @@ -57,7 +59,7 @@ def __init__(self, user_id: str = None, username: str = None, discriminator: str
self._user_id = int(user_id)
else:
if username and discriminator:
member = DiscordPerson.username_and_discriminator_to_userid(username, discriminator)
member = DiscordPerson.resolve_username(username, discriminator)
if member is None:
raise LookupError(
"The user {}#{} can't be found. If you're certain the username "
Expand All @@ -72,7 +74,7 @@ def __init__(self, user_id: str = None, username: str = None, discriminator: str
else:
raise ValueError("Username/discrimator pair or user id not provided.")

self.discord_user = DiscordPerson.client.get_user(int(self._user_id))
self.discord_user = DiscordPerson.client.get_user(self._user_id)
if self.discord_user is None:
raise ValueError(f"Failed to get the user {self._user_id}")

Expand Down
22 changes: 9 additions & 13 deletions src/err-backend-discord/discordlib/room.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,7 @@ def from_id(cls, channel_id):

return cls(channel.name, channel.guild.id, channel.id)

def __init__(
self, channel_name: str = None, guild_id: str = None, channel_id: str = None
):
def __init__(self, channel_name: str = None, guild_id: str = None, channel_id: str = None):
"""
Allows to specify an existing room (via name + guild or via id) or allows the
creation of a future room by specifying a name and guild to create the channel in.
Expand All @@ -55,14 +53,14 @@ def __init__(
if len(channel) == 0:
ValueError(f"Failed to find channel {channel_name} in guild {guild.name}")
if len(channel) > 1:
ValueError(f"More than one channel matched {channel_name} in guild {guild.name}")
ValueError(
f"More than one channel matched {channel_name} in guild {guild.name}"
)
self.discord_channel = channel[0]
else:
raise ValueError(f"Failed to get guild id {guild_id}")
else:
raise ValueError(
"A channel id or channel name + guild id is required for a Room."
)
raise ValueError("A channel id or channel name + guild id is required for a Room.")

def get_discord_object(self):
return self.discord_channel
Expand Down Expand Up @@ -106,9 +104,7 @@ def invite(self, *args) -> None:
raise RuntimeError("Can't invite non Discord Users")

asyncio.run_coroutine_threadsafe(
self.discord_channel.set_permissions(
identifier.discord_user(), read_messages=True
),
self.discord_channel.set_permissions(identifier.discord_user(), read_messages=True),
loop=DiscordRoom.client.loop,
)

Expand Down Expand Up @@ -139,9 +135,9 @@ def create(self) -> None:
log.warning(f"Tried to create {self._channel_name} which already exists.")
raise RoomError("Room exists")

asyncio.run_coroutine_threadsafe(
self.create_room(), loop=DiscordRoom.client.loop
).result(timeout=5)
asyncio.run_coroutine_threadsafe(self.create_room(), loop=DiscordRoom.client.loop).result(
timeout=5
)

def destroy(self) -> None:
if not self.exists:
Expand Down
34 changes: 9 additions & 25 deletions src/err-backend-discord/err-backend-discord.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,10 +116,7 @@ async def on_message(self, msg: discord.Message):
if msg.mentions:
self.callback_mention(
err_msg,
[
DiscordRoomOccupant(mention.id, msg.channel.id)
for mention in msg.mentions
],
[DiscordRoomOccupant(mention.id, msg.channel.id) for mention in msg.mentions],
)

def is_from_self(self, msg: Message) -> bool:
Expand All @@ -138,9 +135,7 @@ async def on_member_update(self, before, after):
if before.status != after.status:
person = DiscordPerson(after.id)

log.debug(
f"Person {person} changed status to {after.status} from {before.status}"
)
log.debug(f"Person {person} changed status to {after.status} from {before.status}")
if after.status == discord.Status.online:
self.callback_presence(Presence(person, ONLINE))
elif after.status == discord.Status.offline:
Expand Down Expand Up @@ -283,9 +278,7 @@ def apply_as_str(bot_intents, intent):
elif isinstance(intent, str):
bot_intents = apply_as_str(bot_intents, intent)
else:
log.warning(
"Unkown intent type %s for '%s'", type(intent), str(intent)
)
log.warning("Unknown intent type %s for '%s'", type(intent), str(intent))
elif isinstance(self.intents, int):
bot_intents = apply_as_int(bot_intents, self.intents)
else:
Expand All @@ -297,9 +290,7 @@ def apply_as_str(bot_intents, intent):
)

log.info(
"Enabled intents - {}".format(
", ".join([i[0] for i in list(bot_intents) if i[1]])
)
"Enabled intents - {}".format(", ".join([i[0] for i in list(bot_intents) if i[1]]))
)
log.info(
"Disabled intents - {}".format(
Expand Down Expand Up @@ -368,8 +359,7 @@ def prefix_groupchat_reply(self, message, identifier: Person):

def rooms(self):
return [
DiscordRoom.from_id(channel.id)
for channel in DiscordBackend.client.get_all_channels()
DiscordRoom.from_id(channel.id) for channel in DiscordBackend.client.get_all_channels()
]

@property
Expand Down Expand Up @@ -421,14 +411,13 @@ def build_identifier(self, text: str):
elif text.startswith("@"):
text = text[1:]
if "#" in text:
user, tag = text.split("#", 1)
return DiscordPerson(username=user, discriminator=tag)
user, discriminator = text.split("#",1)
return DiscordPerson(username=user, discriminator=discriminator)

raise ValueError(f"Invalid representation {text}")

def upload_file(self, msg, filename):
with open(filename, "r") as f:

dest = None
if msg.is_direct:
dest = DiscordPerson(msg.frm.id).get_discord_object()
Expand All @@ -445,12 +434,7 @@ def history(self, channelname, before=None):
mychannel = discord.utils.get(self.client.get_all_channels(), name=channelname)

async def gethist(mychannel, before=None):
return [
i
async for i in self.client.logs_from(mychannel, limit=10, before=before)
]
return [i async for i in self.client.logs_from(mychannel, limit=10, before=before)]

future = asyncio.run_coroutine_threadsafe(
gethist(mychannel, before), loop=self.client.loop
)
future = asyncio.run_coroutine_threadsafe(gethist(mychannel, before), loop=self.client.loop)
return future.result(timeout=None)
4 changes: 1 addition & 3 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,4 @@
import sys

source_path = "../src/err-backend-discord"
sys.path.insert(
0, os.path.abspath(os.path.join(os.path.dirname(__file__), source_path))
)
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), source_path)))
6 changes: 3 additions & 3 deletions tests/test_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,13 @@ def backend():
return discord_backend


def test_build_identifier(backend):
def todo_build_identifier(backend):
raise NotImplementedError


def test_extract_identifiers(backend):
def todo_extract_identifiers(backend):
raise NotImplementedError


def test_send_message(backend):
def todo_send_message(backend):
raise NotImplementedError
30 changes: 15 additions & 15 deletions tests/test_person.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,61 +42,61 @@ def test_create_person_username_and_discriminator():
DiscordPerson(username="someone", discriminator="1234")


def test_wrong_channelid():
def todo_wrong_channelid():
raise NotImplementedError


def test_username():
def todo_username():
raise NotImplementedError


def test_username_not_found():
def todo_username_not_found():
raise NotImplementedError


def test_fullname():
def todo_fullname():
raise NotImplementedError


def test_fullname_not_found():
def todo_fullname_not_found():
raise NotImplementedError


def test_email():
def todo_email():
raise NotImplementedError


def test_email_not_found():
def todo_email_not_found():
raise NotImplementedError


def test_channelname():
def todo_channelname():
raise NotImplementedError


def test_channelname_channel_not_found():
def todo_channelname_channel_not_found():
raise NotImplementedError


def test_domain():
def todo_domain():
raise NotImplementedError


def test_aclattr():
def todo_aclattr():
raise NotImplementedError


def test_person():
def todo_person():
raise NotImplementedError


def test_to_string():
def todo_to_string():
raise NotImplementedError


def test_equal():
def todo_equal():
raise NotImplementedError


def test_hash():
def todo_hash():
raise NotImplementedError
12 changes: 3 additions & 9 deletions tests/test_room.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,19 @@ def discord_room():
def test_create_room_without_arguments():
with pytest.raises(ValueError) as excinfo:
DiscordRoom()
assert "A name or channel id + guild id is required to create a Room." in str(
excinfo.value
)
assert "A name or channel id + guild id is required to create a Room." in str(excinfo.value)


def test_create_room_with_name_only():
with pytest.raises(ValueError) as excinfo:
DiscordRoom(channel_name="#testing_ground")
assert "A name or channel id + guild id is required to create a Room." in str(
excinfo.value
)
assert "A name or channel id + guild id is required to create a Room." in str(excinfo.value)


def test_create_room_with_guild_only():
with pytest.raises(ValueError) as excinfo:
DiscordRoom(guild_id="1234567890123456789")
assert "A name or channel id + guild id is required to create a Room." in str(
excinfo.value
)
assert "A name or channel id + guild id is required to create a Room." in str(excinfo.value)


def test_create_room_with_id(discord_room):
Expand Down
4 changes: 2 additions & 2 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ deps =
twine
build
commands =
python -m build --outdir {distdir}
twine check {distdir}/*
python -m build --outdir {toxworkdir}
twine check {toxworkdir}/*

[testenv:sort]
deps =
Expand Down

0 comments on commit 62e8bf0

Please sign in to comment.