Skip to content

Commit

Permalink
reformatted code with black
Browse files Browse the repository at this point in the history
  • Loading branch information
crucials committed Jul 19, 2024
1 parent c8602ea commit 200abe2
Show file tree
Hide file tree
Showing 21 changed files with 546 additions and 393 deletions.
84 changes: 51 additions & 33 deletions demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,13 @@

from dotenv import load_dotenv

from wiring import (Bot, MultiPlatformMessage, MultiPlatformBot, MultiPlatformUser,
Command)
from wiring import (
Bot,
MultiPlatformMessage,
MultiPlatformBot,
MultiPlatformUser,
Command,
)
from wiring.errors.action_not_supported_error import ActionNotSupportedError
from wiring.platforms.discord import DiscordBot
from wiring.platforms.telegram import TelegramBot
Expand All @@ -14,30 +19,31 @@

load_dotenv()

logging.basicConfig(level=logging.INFO,
format='%(asctime)s: [%(levelname)s] %(name)s - %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p')
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s: [%(levelname)s] %(name)s - %(message)s",
datefmt="%m/%d/%Y %I:%M:%S %p",
)
logger = logging.getLogger()


async def send_commands_list(bot: Bot, message: MultiPlatformMessage,
args: list[str]):
async def send_commands_list(bot: Bot, message: MultiPlatformMessage, args: list[str]):
if message.chat is None:
return

await bot.send_message(
message.chat.id,
'available commands:\n' + '\n'.join(['/' + str(command.name) for command
in bot.commands]),
reply_message_id=message.id
"available commands:\n"
+ "\n".join(["/" + str(command.name) for command in bot.commands]),
reply_message_id=message.id,
)


async def send_greetings(bot: Bot, user: MultiPlatformUser):
if user.from_chat_group is not None:
for chat in await bot.get_chats_from_group(user.from_chat_group.id):
try:
await bot.send_message(chat.id, 'hi ' + user.username)
await bot.send_message(chat.id, "hi " + user.username)
except Exception as error:
logger.error(error)

Expand All @@ -47,31 +53,38 @@ async def ban(bot: Bot, message: MultiPlatformMessage, args: list[str]):
return

if len(args) < 1:
await bot.send_message(message.chat.id, 'specify a name/id of a user',
reply_message_id=message.id)
await bot.send_message(
message.chat.id, "specify a name/id of a user", reply_message_id=message.id
)
return

try:
user = await bot.get_user_by_name(args[0].removeprefix('@'),
message.chat_group.id)
user = await bot.get_user_by_name(
args[0].removeprefix("@"), message.chat_group.id
)

if user is not None:
await bot.ban(message.chat_group.id, user.id)
await bot.send_message(message.chat.id, 'banned',
reply_message_id=message.id)
await bot.send_message(
message.chat.id, "banned", reply_message_id=message.id
)
else:
await bot.send_message(message.chat.id, 'cant find the user',
reply_message_id=message.id)
await bot.send_message(
message.chat.id, "cant find the user", reply_message_id=message.id
)
except ActionNotSupportedError:
await bot.send_message(message.chat.id, 'banning is not supported here',
reply_message_id=message.id)
await bot.send_message(
message.chat.id,
"banning is not supported here",
reply_message_id=message.id,
)


async def send_goodbye(bot: Bot, user: MultiPlatformUser):
if user.from_chat_group is not None:
for chat in await bot.get_chats_from_group(user.from_chat_group.id):
try:
await bot.send_message(chat.id, 'bye ' + user.username)
await bot.send_message(chat.id, "bye " + user.username)
except Exception as error:
logger.error(error)

Expand All @@ -80,20 +93,25 @@ async def start_bots():
bot = MultiPlatformBot()

bot.platform_bots = [
DiscordBot(os.environ['DISCORD_BOT_TOKEN']),
TelegramBot(os.environ['TELEGRAM_BOT_TOKEN']),
TwitchBot(os.environ['TWITCH_BOT_TOKEN'],
streamer_usernames_to_connect=[os.environ['TWITCH_TESTING_CHANNEL']])
DiscordBot(os.environ["DISCORD_BOT_TOKEN"]),
TelegramBot(os.environ["TELEGRAM_BOT_TOKEN"]),
TwitchBot(
os.environ["TWITCH_BOT_TOKEN"],
streamer_usernames_to_connect=[os.environ["TWITCH_TESTING_CHANNEL"]],
),
]

async with bot:
await bot.setup_commands([
Command(['start', 'help', 'help1'], send_commands_list),
Command('ban-user', ban)
], '!')

bot.add_event_handler('join', send_greetings)
bot.add_event_handler('leave', send_goodbye)
await bot.setup_commands(
[
Command(["start", "help", "help1"], send_commands_list),
Command("ban-user", ban),
],
"!",
)

bot.add_event_handler("join", send_greetings)
bot.add_event_handler("leave", send_goodbye)

await bot.listen_to_events()

Expand Down
38 changes: 21 additions & 17 deletions tests/fixtures/multi_platform_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
from dotenv import load_dotenv
import pytest

from tests.errors.missing_environment_variables_error import MissingEnvironmentVariablesError
from tests.errors.missing_environment_variables_error import (
MissingEnvironmentVariablesError,
)
from wiring.multi_platform_bot import MultiPlatformBot
from wiring.platforms.discord import DiscordBot
from wiring.platforms.telegram import TelegramBot
Expand All @@ -16,13 +18,13 @@

class NoBotsAddedError(Exception):
"""at least one platform bot must be added to run tests"""

def __init__(self):
super().__init__('at least one platform bot must be added to run tests')
super().__init__("at least one platform bot must be added to run tests")


async def cancel_pending_asyncio_tasks(event_loop):
pending_tasks = [task for task in asyncio.all_tasks(event_loop)
if not task.done()]
pending_tasks = [task for task in asyncio.all_tasks(event_loop) if not task.done()]

for task in pending_tasks:
task.cancel()
Expand All @@ -33,29 +35,31 @@ async def cancel_pending_asyncio_tasks(event_loop):
pass


@pytest.fixture(scope='session')
@pytest.fixture(scope="session")
async def multi_platform_bot():
bot = MultiPlatformBot()

if 'DISCORD_BOT_TOKEN' in os.environ:
bot.platform_bots.append(DiscordBot(os.environ['DISCORD_BOT_TOKEN']))
if "DISCORD_BOT_TOKEN" in os.environ:
bot.platform_bots.append(DiscordBot(os.environ["DISCORD_BOT_TOKEN"]))

if 'TELEGRAM_BOT_TOKEN' in os.environ:
bot.platform_bots.append(TelegramBot(os.environ['TELEGRAM_BOT_TOKEN']))
if "TELEGRAM_BOT_TOKEN" in os.environ:
bot.platform_bots.append(TelegramBot(os.environ["TELEGRAM_BOT_TOKEN"]))

if 'TWITCH_BOT_TOKEN' in os.environ:
testing_channel = os.environ.get('TWITCH_TESTING_CHANNEL')
if "TWITCH_BOT_TOKEN" in os.environ:
testing_channel = os.environ.get("TWITCH_TESTING_CHANNEL")

if testing_channel is None:
raise MissingEnvironmentVariablesError(
'to test twitch bot, you must specify a twitch channel id '
+ 'for testing like that:\nTWITCH_TESTING_CHANNEL=<streamer username>'
"to test twitch bot, you must specify a twitch channel id "
+ "for testing like that:\nTWITCH_TESTING_CHANNEL=<streamer username>"
)

bot.platform_bots.append(TwitchBot(
os.environ['TWITCH_BOT_TOKEN'],
streamer_usernames_to_connect=[testing_channel]
))
bot.platform_bots.append(
TwitchBot(
os.environ["TWITCH_BOT_TOKEN"],
streamer_usernames_to_connect=[testing_channel],
)
)

if len(bot.platform_bots) == 0:
raise NoBotsAddedError()
Expand Down
38 changes: 22 additions & 16 deletions tests/test_discord_bot_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,38 +10,44 @@
logger = logging.getLogger()


@pytest.mark.asyncio(scope='session')
@pytest.mark.asyncio(scope="session")
async def test_message_sending(multi_platform_bot: MultiPlatformBot):
discord_bots = [bot for bot in multi_platform_bot.platform_bots
if bot.platform == 'discord']
discord_bots = [
bot for bot in multi_platform_bot.platform_bots if bot.platform == "discord"
]

if len(discord_bots) == 0:
pytest.skip('skipping discord bot actions testing because it\'s not added '
+ 'via DISCORD_BOT_TOKEN environment variable')
pytest.skip(
"skipping discord bot actions testing because it's not added "
+ "via DISCORD_BOT_TOKEN environment variable"
)

guilds = await multi_platform_bot.get_chat_groups('discord')
guilds = await multi_platform_bot.get_chat_groups("discord")

if len(guilds) == 0:
raise UnusableBotError('current discord bot must be at least in one guild to '
+ 'run this test')
raise UnusableBotError(
"current discord bot must be at least in one guild to " + "run this test"
)

channels = await multi_platform_bot.get_chats_from_group({'platform': 'discord',
'value': guilds[0].id})
channels = await multi_platform_bot.get_chats_from_group(
{"platform": "discord", "value": guilds[0].id}
)
assert len(channels) > 0

guild_has_messageable_channels = False

for channel in channels:
try:
await multi_platform_bot.send_message({
'discord': channel.id
}, 'test message')
await multi_platform_bot.send_message(
{"discord": channel.id}, "test message"
)

guild_has_messageable_channels = True
break
except NotMessageableChatError:
logger.debug(f'channel \'{channel.name}\' cant be messaged')
logger.debug(f"channel '{channel.name}' cant be messaged")

if not guild_has_messageable_channels:
raise UnusableBotError('current discord bot first guild must have a '
+ 'messageable channel')
raise UnusableBotError(
"current discord bot first guild must have a " + "messageable channel"
)
37 changes: 22 additions & 15 deletions tests/test_telegram_bot_actions.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,35 @@
import os
import pytest

from tests.errors.missing_environment_variables_error import MissingEnvironmentVariablesError
from tests.errors.missing_environment_variables_error import (
MissingEnvironmentVariablesError,
)
from wiring.multi_platform_bot import MultiPlatformBot


@pytest.mark.asyncio(scope='session')
@pytest.mark.asyncio(scope="session")
async def test_message_sending(multi_platform_bot: MultiPlatformBot):
telegram_bots = [bot for bot in multi_platform_bot.platform_bots
if bot.platform == 'telegram']
telegram_bots = [
bot for bot in multi_platform_bot.platform_bots if bot.platform == "telegram"
]

if len(telegram_bots) == 0:
pytest.skip('skipping telegram bot actions testing because it\'s not added '
+ 'via TELEGRAM_BOT_TOKEN environment variable')
pytest.skip(
"skipping telegram bot actions testing because it's not added "
+ "via TELEGRAM_BOT_TOKEN environment variable"
)

testing_chat_id = os.environ.get('TELEGRAM_TESTING_CHAT_ID')
testing_chat_id = os.environ.get("TELEGRAM_TESTING_CHAT_ID")

if testing_chat_id is None:
raise MissingEnvironmentVariablesError('it\'s not possible to get current '
+ 'bot chats with telegram api. so '
+ 'you must specify some testing chat id '
+ 'in `.env` file like that: '
+ 'TELEGRAM_TESTING_CHAT_ID=<id here>')
raise MissingEnvironmentVariablesError(
"it's not possible to get current "
+ "bot chats with telegram api. so "
+ "you must specify some testing chat id "
+ "in `.env` file like that: "
+ "TELEGRAM_TESTING_CHAT_ID=<id here>"
)

await multi_platform_bot.send_message({
'telegram': int(testing_chat_id)
}, 'test message')
await multi_platform_bot.send_message(
{"telegram": int(testing_chat_id)}, "test message"
)
19 changes: 10 additions & 9 deletions tests/test_twitch_bot_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,20 @@
from wiring.multi_platform_bot import MultiPlatformBot


@pytest.mark.asyncio(scope='session')
@pytest.mark.asyncio(scope="session")
async def test_message_sending(multi_platform_bot: MultiPlatformBot):
twitch_bots = [bot for bot in multi_platform_bot.platform_bots
if bot.platform == 'twitch']
twitch_bots = [
bot for bot in multi_platform_bot.platform_bots if bot.platform == "twitch"
]

if len(twitch_bots) == 0:
pytest.skip('skipping twitch bot actions testing because it\'s not added '
+ 'via TWITCH_BOT_TOKEN environment variable')
pytest.skip(
"skipping twitch bot actions testing because it's not added "
+ "via TWITCH_BOT_TOKEN environment variable"
)

channels = await multi_platform_bot.get_chat_groups('twitch')
channels = await multi_platform_bot.get_chat_groups("twitch")

assert len(channels) > 0

await multi_platform_bot.send_message({
'twitch': channels[0].id
}, 'test message')
await multi_platform_bot.send_message({"twitch": channels[0].id}, "test message")
14 changes: 10 additions & 4 deletions wiring/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
from wiring.multi_platform_bot import MultiPlatformBot, PlatformBotNotFoundError
from wiring.multi_platform_resources import (PlatformSpecificValue, MultiPlatformChat,
MultiPlatformChatGroup, MultiPlatformId,
MultiPlatformMessage, MultiPlatformUser,
MultiPlatformValue, Platform)
from wiring.multi_platform_resources import (
PlatformSpecificValue,
MultiPlatformChat,
MultiPlatformChatGroup,
MultiPlatformId,
MultiPlatformMessage,
MultiPlatformUser,
MultiPlatformValue,
Platform,
)
from wiring.bot_base import Bot, Command, CommandHandler
Loading

0 comments on commit 200abe2

Please sign in to comment.