1
Fork 0
mirror of https://github.com/RYGhub/royalnet.git synced 2024-11-23 19:44:20 +00:00

Port a few commands to the new format

This commit is contained in:
Steffo 2019-08-24 00:50:21 +02:00
parent b6ffbef521
commit 51e7ef80be
37 changed files with 232 additions and 55 deletions

View file

@ -24,10 +24,10 @@ class GenericBot:
self._Interface = self._interface_factory() self._Interface = self._interface_factory()
self._Data = self._data_factory() self._Data = self._data_factory()
self.commands = {} self.commands = {}
self.network_handlers: typing.Dict[str, typing.Type[NetworkHandler]] = {}
for SelectedCommand in commands: for SelectedCommand in commands:
interface = self._Interface() interface = self._Interface()
self.commands[f"{interface.prefix}{SelectedCommand.name}"] = SelectedCommand(interface) self.commands[f"{interface.prefix}{SelectedCommand.name}"] = SelectedCommand(interface)
self.network_handlers: typing.Dict[str, typing.Type[NetworkHandler]] = {}
log.debug(f"Successfully bound commands") log.debug(f"Successfully bound commands")
def _interface_factory(self) -> typing.Type[CommandInterface]: def _interface_factory(self) -> typing.Type[CommandInterface]:

View file

@ -13,7 +13,7 @@ class Command:
description: str = NotImplemented description: str = NotImplemented
"""A small description of the command, to be displayed when the command is being autocompleted.""" """A small description of the command, to be displayed when the command is being autocompleted."""
syntax: str = NotImplemented syntax: str = ""
"""The syntax of the command, to be displayed when a :py:exc:`royalnet.error.InvalidInputError` is raised, """The syntax of the command, to be displayed when a :py:exc:`royalnet.error.InvalidInputError` is raised,
in the format ``(required_arg) [optional_arg]``.""" in the format ``(required_arg) [optional_arg]``."""

View file

@ -4,5 +4,11 @@ These probably won't suit your needs, as they are tailored for the bots of the R
may be useful to develop new ones.""" may be useful to develop new ones."""
from .ping import PingCommand from .ping import PingCommand
from .ciaoruozi import CiaoruoziCommand
from .color import ColorCommand
from .cv import CvCommand
__all__ = ["PingCommand"] __all__ = ["PingCommand",
"CiaoruoziCommand",
"ColorCommand",
"CvCommand"]

View file

@ -1,22 +1,25 @@
from ..utils import Command, Call import typing
from telegram import Update, User import telegram
from ..command import Command
from ..commandinterface import CommandInterface
from ..commandargs import CommandArgs
from ..commanddata import CommandData
class CiaoruoziCommand(Command): class CiaoruoziCommand(Command):
name: str = "ciaoruozi"
command_name = "ciaoruozi" description: str = "Saluta Ruozi, un leggendario essere che una volta era in Royal Games."
command_description = "Saluta Ruozi, anche se non è più in RYG."
command_syntax = ""
@classmethod syntax: str = ""
async def common(cls, call: "Call"):
await call.reply("👋 Ciao Ruozi!")
@classmethod require_alchemy_tables: typing.Set = set()
async def telegram(cls, call: Call):
update: Update = call.kwargs["update"] async def run(self, args: CommandArgs, data: CommandData) -> None:
user: User = update.effective_user if self.interface.name == "telegram":
if user.id == 112437036: update: telegram.Update = data.update
await call.reply("👋 Ciao me!") user: telegram.User = update.effective_user
else: if user.id == 112437036:
await call.reply("👋 Ciao Ruozi!") await data.reply("👋 Ciao me!")
return
await data.reply("👋 Ciao Ruozi!")

View file

@ -1,14 +1,16 @@
from ..utils import Command, Call import typing
from ..command import Command
from ..commandinterface import CommandInterface
from ..commandargs import CommandArgs
from ..commanddata import CommandData
class ColorCommand(Command): class ColorCommand(Command):
name: str = "color"
command_name = "color" description: str = "Invia un colore in chat...?"
command_description = "Invia un colore in chat...?"
command_syntax = ""
@classmethod async def run(self, args: CommandArgs, data: CommandData) -> None:
async def common(cls, call: Call): await data.reply("""
await call.reply(""" [i]I am sorry, unknown error occured during working with your request, Admin were notified[/i]
[i]I am sorry, unknown error occured during working with your request, Admin were notified[/i] """)
""")

View file

@ -1,11 +1,13 @@
import typing
import discord import discord
import asyncio import typing
from ..utils import Command, Call, NetworkHandler, andformat from ..command import Command
from ..network import Request, ResponseSuccess from ..commandinterface import CommandInterface
from ..error import NoneFoundError, TooManyFoundError from ..commandargs import CommandArgs
if typing.TYPE_CHECKING: from ..commanddata import CommandData
from ..bots import DiscordBot from ...network import Request, ResponseSuccess
from ...utils import NetworkHandler, andformat
from ...bots import DiscordBot
from ...error import *
class CvNH(NetworkHandler): class CvNH(NetworkHandler):
@ -41,14 +43,14 @@ class CvNH(NetworkHandler):
# Edit the message, sorted by channel # Edit the message, sorted by channel
for channel in sorted(channels, key=lambda c: -c): for channel in sorted(channels, key=lambda c: -c):
members_in_channels[channel].sort(key=lambda x: x.nick if x.nick is not None else x.name) members_in_channels[channel].sort(key=lambda x: x.nick if x.nick is not None else x.name)
if channel == 0: if channel == 0 and len(members_in_channels[0]) > 0:
message += "[b]Non in chat vocale:[/b]\n" message += "[b]Non in chat vocale:[/b]\n"
else: else:
message += f"[b]In #{channels[channel].name}:[/b]\n" message += f"[b]In #{channels[channel].name}:[/b]\n"
for member in members_in_channels[channel]: for member in members_in_channels[channel]:
member: typing.Union[discord.User, discord.Member] member: typing.Union[discord.User, discord.Member]
# Ignore not-connected non-notable members # Ignore not-connected non-notable members
if not data["full"] and channel == 0 and len(member.roles) < 2: if not data["everyone"] and channel == 0 and len(member.roles) < 2:
continue continue
# Ignore offline members # Ignore offline members
if member.status == discord.Status.offline and member.voice is None: if member.status == discord.Status.offline and member.voice is None:
@ -113,15 +115,20 @@ class CvNH(NetworkHandler):
class CvCommand(Command): class CvCommand(Command):
name: str = "cv"
command_name = "cv" description: str = "Elenca le persone attualmente connesse alla chat vocale."
command_description = "Elenca le persone attualmente connesse alla chat vocale."
command_syntax = "[guildname]"
network_handlers = [CvNH] syntax: str = "[guildname] "
@classmethod def __init__(self, interface: CommandInterface):
async def common(cls, call: Call): super().__init__(interface)
guild_name = call.args.optional(0) interface.register_net_handler("discord_cv", CvNH)
response = await call.net_request(Request("discord_cv", {"guild_name": guild_name, "full": False}), "discord")
await call.reply(response["response"]) async def run(self, args: CommandArgs, data: CommandData) -> None:
# noinspection PyTypeChecker
guild_name, everyone = args.match(r"(?:\[(.+)])?\s*(\S+)?\s*")
response = await self.interface.net_request(Request("discord_cv", {"guild_name": guild_name,
"everyone": bool(everyone)}),
destination="discord")
await data.reply(response["response"])

View file

@ -0,0 +1,22 @@
from ..utils import Command, Call
from telegram import Update, User
class CiaoruoziCommand(Command):
command_name = "ciaoruozi"
command_description = "Saluta Ruozi, anche se non è più in RYG."
command_syntax = ""
@classmethod
async def common(cls, call: "Call"):
await call.reply("👋 Ciao Ruozi!")
@classmethod
async def telegram(cls, call: Call):
update: Update = call.kwargs["update"]
user: User = update.effective_user
if user.id == 112437036:
await call.reply("👋 Ciao me!")
else:
await call.reply("👋 Ciao Ruozi!")

View file

@ -0,0 +1,14 @@
from ..utils import Command, Call
class ColorCommand(Command):
command_name = "color"
command_description = "Invia un colore in chat...?"
command_syntax = ""
@classmethod
async def common(cls, call: Call):
await call.reply("""
[i]I am sorry, unknown error occured during working with your request, Admin were notified[/i]
""")

View file

@ -0,0 +1,127 @@
import typing
import discord
import asyncio
from ..utils import Command, Call, NetworkHandler, andformat
from ..network import Request, ResponseSuccess
from ..error import NoneFoundError, TooManyFoundError
if typing.TYPE_CHECKING:
from ..bots import DiscordBot
class CvNH(NetworkHandler):
message_type = "discord_cv"
@classmethod
async def discord(cls, bot: "DiscordBot", data: dict):
# Find the matching guild
if data["guild_name"]:
guild: discord.Guild = bot.client.find_guild_by_name(data["guild_name"])
else:
if len(bot.client.guilds) == 0:
raise NoneFoundError("No guilds found")
if len(bot.client.guilds) > 1:
raise TooManyFoundError("Multiple guilds found")
guild = list(bot.client.guilds)[0]
# Edit the message, sorted by channel
discord_members = list(guild.members)
channels = {0: None}
members_in_channels = {0: []}
message = ""
# Find all the channels
for member in discord_members:
if member.voice is not None:
channel = members_in_channels.get(member.voice.channel.id)
if channel is None:
members_in_channels[member.voice.channel.id] = list()
channel = members_in_channels[member.voice.channel.id]
channels[member.voice.channel.id] = member.voice.channel
channel.append(member)
else:
members_in_channels[0].append(member)
# Edit the message, sorted by channel
for channel in sorted(channels, key=lambda c: -c):
members_in_channels[channel].sort(key=lambda x: x.nick if x.nick is not None else x.name)
if channel == 0:
message += "[b]Non in chat vocale:[/b]\n"
else:
message += f"[b]In #{channels[channel].name}:[/b]\n"
for member in members_in_channels[channel]:
member: typing.Union[discord.User, discord.Member]
# Ignore not-connected non-notable members
if not data["full"] and channel == 0 and len(member.roles) < 2:
continue
# Ignore offline members
if member.status == discord.Status.offline and member.voice is None:
continue
# Online status emoji
if member.bot:
message += "🤖 "
elif member.status == discord.Status.online:
message += "🔵 "
elif member.status == discord.Status.idle:
message += "⚫️ "
elif member.status == discord.Status.dnd:
message += "🔴 "
elif member.status == discord.Status.offline:
message += "⚪️ "
# Voice
if channel != 0:
# Voice status
if member.voice.afk:
message += "💤 "
elif member.voice.self_deaf or member.voice.deaf:
message += "🔇 "
elif member.voice.self_mute or member.voice.mute:
message += "🔈 "
elif member.voice.self_video:
message += "📺 "
else:
message += "🔊 "
# Nickname
if member.nick is not None:
message += f"[i]{member.nick}[/i]"
else:
message += member.name
# Game or stream
if member.activity is not None:
if member.activity.type == discord.ActivityType.playing:
message += f" | 🎮 {member.activity.name}"
# Rich presence
try:
if member.activity.state is not None:
message += f" ({member.activity.state}" \
f" | {member.activity.details})"
except AttributeError:
pass
elif member.activity.type == discord.ActivityType.streaming:
message += f" | 📡 {member.activity.url}"
elif member.activity.type == discord.ActivityType.listening:
if isinstance(member.activity, discord.Spotify):
if member.activity.title == member.activity.album:
message += f" | 🎧 {member.activity.title} ({andformat(member.activity.artists, final=' e ')})"
else:
message += f" | 🎧 {member.activity.title} ({member.activity.album} | {andformat(member.activity.artists, final=' e ')})"
else:
message += f" | 🎧 {member.activity.name}"
elif member.activity.type == discord.ActivityType.watching:
message += f" | 📺 {member.activity.name}"
else:
message += f" | ❓ Unknown activity"
message += "\n"
message += "\n"
return ResponseSuccess({"response": message})
class CvCommand(Command):
command_name = "cv"
command_description = "Elenca le persone attualmente connesse alla chat vocale."
command_syntax = "[guildname]"
network_handlers = [CvNH]
@classmethod
async def common(cls, call: Call):
guild_name = call.args.optional(0)
response = await call.net_request(Request("discord_cv", {"guild_name": guild_name, "full": False}), "discord")
await call.reply(response["response"])

View file

@ -10,12 +10,5 @@ class PingCommand(Command):
description: str = "Replies with a Pong!" description: str = "Replies with a Pong!"
syntax: str = ""
require_alchemy_tables: typing.Set = set()
def __init__(self, interface: CommandInterface):
super().__init__(interface)
async def run(self, args: CommandArgs, data: CommandData) -> None: async def run(self, args: CommandArgs, data: CommandData) -> None:
await data.reply("Pong!") await data.reply("🏓 Pong!")

View file

@ -16,7 +16,10 @@ stream_handler = logging.StreamHandler()
stream_handler.formatter = logging.Formatter("{asctime}\t{name}\t{levelname}\t{message}", style="{") stream_handler.formatter = logging.Formatter("{asctime}\t{name}\t{levelname}\t{message}", style="{")
log.addHandler(stream_handler) log.addHandler(stream_handler)
commands = [PingCommand] commands = [PingCommand,
ColorCommand,
CiaoruoziCommand,
CvCommand]
# noinspection PyUnreachableCode # noinspection PyUnreachableCode
if __debug__: if __debug__: