def __init__(self, *, state, data): self._state = state self.id = int(data["id"]) self.type = try_enum(InteractionType, data["type"]) self.data = "data" in data and InteractionData(data["data"]) self.guild_id = _get_as_snowflake(data, "guild_id") self.channel_id = _get_as_snowflake(data, "channel_id") self.author = ( ("member" in data and Member(data=data["member"], guild=guild, state=state) if (guild := state._get_guild(self.guild_id)) else User( state=state, data=data["member"]["user"])) or "user" in data and User(state=state, data=data["user"])) self.token = data["token"] self.version = data["version"]
async def wait_for_button_click(self, message: Message, check=None, timeout: float = None): res = await self.bot.wait_for("socket_response", check=check, timeout=timeout) if res["t"] != "INTERACTION_CREATE": return None button_id = res["d"]["data"]["custom_id"] resbutton = None for buttons in res["d"]["message"]["components"]: for button in buttons["components"]: if button["style"] == 5: continue if button["custom_id"] == button_id: resbutton = button ctx = Context( bot=self.bot, client=self, message=message, user=User(state=self.bot._get_state(), data=res["d"]["member"]["user"]), button=Button( style=resbutton["style"], label=resbutton["label"], id=resbutton["custom_id"], ), interaction_id=res["d"]["id"], raw_data=res, interaction_token=res["d"]["token"], ) return ctx
async def get_user_info(self): try: return user_id_cache[self.refresh_token] except KeyError: async with self as http: rtn = user_id_cache[self.refresh_token] = User( data=await http.get_user("@me"), state=NotImplemented) return rtn
def on_alert(): users = get_users() for user in users: user = User('', user, '', '') client.send_message(user, 'MapleStory is back online!') clear_users()
async def on_socket_response(msg): t = msg["t"] d = msg["d"] if t == "INTERACTION_CREATE": command_data = d["data"] command_name = command_data["name"] command_id = command_data["id"] command_args = [] subcommand = None if command_data.get("options"): for arg in command_data["options"]: if arg.get("value") is not None: command_args.append([arg["name"], arg["value"]]) else: subcommand = arg["name"] interaction_id = d["id"] interaction_token = d["token"] channel_id = int(d["channel_id"]) guild_id = int(d["guild_id"]) if d.get("guild_id") else None user_data = d.get("member") or d.get("user") if not guild_id: return guild = guild_id and Bloxlink.get_guild(guild_id) user = None channel = None if guild: user = Member(state=guild._state, data=user_data, guild=guild) channel = find(lambda c: c.id == channel_id, guild.text_channels) else: user = User(state=Bloxlink._connection, data=user_data) channel = DMChannel(me=Bloxlink.user, state=Bloxlink._connection, data={ "id": channel_id, "recipients": [user_data] }) try: await handle_slash_command(command_name, guild=guild, channel=channel, user=user, interaction_id=interaction_id, interaction_token=interaction_token, command_id=command_id, subcommand=subcommand, arguments=command_args) except CancelCommand: pass
def discord_user(discord_connection): from discord import User return User(data={ "id": 1, "username": "******", "discriminator": "0001", "avatar": "" }, state=discord_connection)
async def wait_for_button_click( self, message: ButtonMessage, check: Callable[[Context], Awaitable[bool]] = None, timeout: float = None, ) -> Context: """A function that waits until a user clicks a button on the message :returns: :class:`~discord_buttons.Context` Parameters ---------- message: :class:`~discord_buttons.ButtonMessage` The message check: Optional[Callable[[:class:`Context`], Coroutine[:class:`bool`]]] The wait_for check function timeout: Optional[:class:`float`] The wait_for timeout """ while True: res = await self.bot.wait_for("socket_response", check=check, timeout=timeout) if res["t"] != "INTERACTION_CREATE": continue if message.id != int(res["d"]["message"]["id"]): continue break button_id = res["d"]["data"]["custom_id"] resbutton = None for buttons in res["d"]["message"]["components"]: for button in buttons["components"]: if button["style"] == 5: continue if button["custom_id"] == button_id: resbutton = button ctx = Context( bot=self.bot, client=self, user=User(state=self.bot._get_state(), data=res["d"]["member"]["user"]), button=Button( style=resbutton["style"], label=resbutton["label"], id=resbutton["custom_id"], ), raw_data=res, message=message, ) return ctx
async def dispatch(self, rem): try: log.debug("Dispatching") if rem.get("type") == REMINDER_PERSONAL: receiver = User(id=rem.get("receiver")) else: receiver = Object(id=rem.get("receiver")) await self.client.send_message(receiver, rem.get("content")) except DiscordException as e: log.warning(e)
def authors(): authors = [ 'a', 'b', 'pete', 'spacey name', '1 name number', 'loser1111111111111' ] for i, name in enumerate(authors): user_data = { 'username': name, 'id': i, 'discriminator': name, 'avatar': 'http' + name } authors[i] = User(state=None, data=user_data) return authors
async def _on_send_message(self, msg): if not self.config.get("broadcaster_channels", None): print("No broadcast channels configured for %s" % self) return for chanid in self.config["broadcaster_channels"]: channel = self.client.get_channel(chanid) # If the channel was not found, maybe it's a user id for DM if not channel: channel = await self.client.start_private_message( User(id=chanid)) if channel: await self.client.send_message(channel, msg)
async def enable_command(self, server_id, command, user_id=None): log.debug(f'enabling {command} command for server {server_id}') plugin_name = self._plugin_for_cmd(command) if not plugin_name: return False if not self.mbot.perms_check(User(id=user_id), su=True): # Skip Core plugin. if plugin_name == 'Core': return False # Skip 'su' commands if not superuser if self.commands[command][2].info['perms'][0]: return False doc = await self.mbot.mongo.config.find_one({ 'server_id': server_id, 'plugins': { '$elemMatch': { 'name': plugin_name } } }) commands = await self.commands_for_server(server_id) # Command is already enabled. if command in commands: return False if doc is not None: ret = await self.mbot.mongo.config.update_one( { 'server_id': server_id, 'plugins': { '$elemMatch': { 'name': plugin_name } } }, {'$push': { 'plugins.$.commands': command }}) return bool(ret)
def __init__(self, data: Dict[str, Any], state: ConnectionState) -> None: self._state = state self.responded = False self.id = int(data["id"]) self.application_id = int(data["application_id"]) self.type = InteractionType(int(data["type"])) self.guild_id = int(data["guild_id"]) if "guild_id" in data else None self.channel_id = int( data["channel_id"]) if "channel_id" in data else None self.member = (InteractionMember( data=data["member"], state=state, guild=self.guild) if "member" else None) self.user = ( User(data=data["user"], state=self._state) if "user" in data else None # type: ignore ) self.token = data["token"] self.version = int(data["version"])
async def on_message(message): # Ignore the messages from the bot itself if message.author == client.user: return # Find out if we recognize this user from previous sessions, thus it needs to be in our own database # If it doesn't exists, create the user for tracking it's unique ID user = User() user.get_user(message.author.id) if message.channel.name == 'reservations-wednesday': channel = message.channel # print('Great, this message is coming from the reservations channel') await channel.send(f'Thank you, {message.author.name}, we will process your reservation!') if message.content.startswith('$reserve'): print('Someone is trying to reserve', message.content) elif message.content.startswith('$unreserve'): print('Unreserving nation', message.content) else: print('Not much happening')
async def on_interaction(interaction): data = interaction.data command_name = interaction.data.get("name") command_args = {} guild = interaction.guild channel = interaction.channel user = interaction.user if isinstance(channel, PartialMessageable): return if data["type"] == 2: # context menu command resolved = None if data.get("resolved"): if data["resolved"].get("users"): resolved = User(state=interaction._state, data=list( data["resolved"]["users"].values())[0]) else: resolved = Message( state=interaction._state, channel=channel, data=list(data["resolved"]["messages"].values())[0]) try: await execute_interaction_command("extensions", command_name, guild=guild, channel=channel, user=user, interaction=interaction, resolved=resolved) except CancelCommand: pass elif data["type"] == 1: # slash command if not command_name: return subcommand = None focused_option = None if data.get("options"): if RELEASE == "LOCAL": print(data["options"]) for arg in data["options"]: if arg.get("options"): subcommand = arg["name"] for arg2 in arg["options"]: if arg2.get("focused"): focused_option = arg2 command_args[arg2["name"]] = arg2["value"] else: if arg.get("value") is not None: if arg.get("focused"): focused_option = arg command_args[arg["name"]] = arg["value"] else: subcommand = arg["name"] if focused_option: await send_autocomplete_options(interaction, command_name, subcommand, command_args, focused_option) return # execute slash command try: await execute_interaction_command("commands", command_name, guild=guild, channel=channel, user=user, interaction=interaction, subcommand=subcommand, arguments=command_args) except CancelCommand: pass
def is_user_su(self, user_id): return self.mbot.perms_check(User(id=user_id), su=True)
async def on_socket_response(self, msg: JSON): """ Event handler for socket response event in discord.py :param msg: gateway payload received in discord.py client's websocket. """ if msg['t'] != 'INTERACTION_CREATE': # This event handler only handles 'INTERACTION_CREATE' event, so other events are dismissed. return btn_logger.debug( "ButtonHandler : 'INTERACTION_CREATE' Event received in websocket. Debugging gateway payload :\n{}" .format(json.dumps(msg, ensure_ascii=False, indent=2))) data = msg['d'] btn_logger.debug( 'ButtonHandler : Event data from gateway payload : {}'.format( json.dumps(data, ensure_ascii=False, indent=2))) custom_id = data['data']['custom_id'] btn: Optional[Button] = ButtonCache().get_button(custom_id) btn_logger.debug(f'btn : {btn}') if btn is not None: data = msg['d'] state = self._get_state() channel_id: int = data['channel_id'] btn_logger.debug(f'channel.id : {channel_id}') if 'guild_id' in data and 'member' in data: # Interaction from guild guild_id: int = data['guild_id'] btn_logger.debug( 'Interaction from guild : id = {}'.format(guild_id)) guild: Optional[Guild] = self.get_guild(guild_id) btn_logger.debug('- Guild : {}'.format(guild)) if guild is not None: member: Member = Member(data=data['member'], guild=guild, state=state) btn_logger.debug('member : {}'.format(member)) channel: Optional[Messageable] = guild.get_channel( channel_id) btn_logger.debug( 'guild.get_channel(channel.id) : {}'.format(channel)) msg: ComponentMessage = ComponentMessage(state=state, channel=channel, data=data['message']) await btn.invoke( ButtonContext(msg, member, btn, data['id'], raw_data=data)) elif 'user' in data: # Interaction from channel user: User = User(data=data['user'], state=state) btn_logger.debug('user : {}'.format(user)) channel: Optional[Messageable] = self.get_channel(channel_id) btn_logger.debug( 'Client.get_channel(channel.id) : {}'.format(channel)) msg: ComponentMessage = ComponentMessage(state=state, channel=channel, data=data['message']) await btn.invoke( ButtonContext(msg, user, btn, data['id'], raw_data=data))