async def log_error(self, error:str): webhook_url = f"https://discordapp.com/api/webhooks/{config.webhook_id}/{config.webhook_token}" webhook = discord.Webhook.from_url(webhook_url, adapter=discord.AsyncWebhookAdapter(self.session)) em = discord.Embed(color=0xff6f3f) em.title = "Error" em.description = chat_formatting.box(error, "python") em.set_footer(text="Instance %s" % self.bot.instance) await webhook.send(embed=em)
def webhook(self): config = self.bot._config wh_id = config.get('WH', '_id') wh_token = config.get('WH', '_key') hook = discord.Webhook.partial(id=wh_id, token=wh_token, adapter=discord.AsyncWebhookAdapter( self.bot.session)) return hook
async def _start(self, url, handler): async with aiohttp.ClientSession() as session: if self._last_url == url: return self._last_webhook else: _webhook = discord.Webhook.from_url( url, adapter=discord.AsyncWebhookAdapter(handler._session)) self._last_webhook = _webhook self._last_url = url return self._last_webhook
async def webhook_update(self, ctx, *, args=None): if await self.client.is_owner(ctx.author): if args: if isinstance(ctx.channel, discord.TextChannel): await ctx.message.delete() session = self.client.session webhook = discord.Webhook.from_url( os.environ["webhook1"], adapter=discord.AsyncWebhookAdapter(session), ) embed = discord.Embed( title="Update", color=(35056), timestamp=(ctx.message.created_at), ) embed.add_field(name="Update Info:", value=args) embed.set_author( name="JDJG's Update", icon_url="https://i.imgur.com/pdQkCBv.png") embed.set_footer(text="JDJG's Updates") await webhook.execute(embed=embed) session = self.client.session webhook = discord.Webhook.from_url( os.environ["webhook99"], adapter=discord.AsyncWebhookAdapter(session), ) embed = discord.Embed( title="Update", color=(35056), timestamp=(ctx.message.created_at), ) embed.add_field(name="Update Info:", value=args) embed.set_author( name="JDJG's Update", icon_url="https://i.imgur.com/pdQkCBv.png") embed.set_footer(text="JDJG's Updates") await webhook.execute(embed=embed) if args is None: await ctx.send("You sadly can't use it like that.") if await self.client.is_owner(ctx.author) is False: await ctx.send("You can't use that")
def _resolve_channel(self, channel): dc_channel = self._get_channel(channel) webhook = None for label, host_channel in self.host.channels.items(): if channel == host_channel and label in self.config["webhooks"]: adapter = discord.AsyncWebhookAdapter(self.session) webhook = discord.Webhook.from_url( self.config["webhooks"][label], adapter=adapter) break return dc_channel, webhook
async def __post_to_hook(self, action: str, user: discord.Member, amount): try: async with aiohttp.ClientSession() as cs: webhook = discord.Webhook.from_url( hooks.get_url(), adapter=discord.AsyncWebhookAdapter(cs)) await webhook.send( "User: %s (%s)\nAction: %s\nAmount: %s\nTime: %s" % (str(user), user.id, action, amount, int(time.time()))) except: pass
async def on_guild_remove(self, guild): """Sends the name and membercount of every server the bot leaves""" async with aiohttp.ClientSession() as session: webhook = discord.Webhook.from_url( 'https://discordapp.com/api/webhooks/744353242322043001/V3WMdShI8L8LZLStNUBaqG2WI-qZrdofCQFM1QkW4oLTIcRA4TMC5ffKFpS2JyIXp96w', adapter=discord.AsyncWebhookAdapter(session)) await webhook.send( f'StalkerBot was removed from `{guild.name}` (`{guild.id}`). `{len([i for i in guild.members if not i.bot])}` members.', username='******')
async def report(self, ctx, url, is_rick_roll: bool): """Report a rickroll that the bot failed to detect, or a normal URL that the bot thought was a rickroll.""" hook = discord.Webhook.from_url(auth.WEBHOOKS['reports'], adapter=discord.AsyncWebhookAdapter( self.bot.session)) await hook.send(f"⚠ **New report:**\n" f"User: {ctx.author} (`{ctx.author.id}`)\n" f"URL: `{url}`\n" f"is_rick_roll: {is_rick_roll}") await ctx.send("Sent!")
async def stopbooru(self, ctx: commands.Context): async with aiohttp.ClientSession() as session: if hook := await q.Hook(self.bot, ctx.guild.id, ctx.channel.id).get(): await q.Hook(self.bot, ctx.guild.id, ctx.channel.id).delete() webhook = discord.Webhook.from_url( hook.hookurl, adapter=discord.AsyncWebhookAdapter(session)) await webhook.send(f"Webhookの登録を解除しました") await webhook.delete() else:
async def on_command_error(self, ctx, exception): error = getattr(exception, "original", exception) if isinstance(error, discord.NotFound): return elif isinstance(error, discord.Forbidden): return elif isinstance(error, discord.HTTPException) or isinstance(error, aiohttp.ClientConnectionError): async with aiohttp.ClientSession() as cs: webhook = discord.Webhook.from_url(self.webhook_url, adapter=discord.AsyncWebhookAdapter(cs)) em = discord.Embed(color=16740159) em.title = "Error in command %s, Instance %s" % (ctx.command.qualified_name, self.bot.instance) em.description = "HTTPException" await webhook.send(embed=em) _ = await self._get_text(ctx) return await ctx.send(_("Failed to get data.")) if isinstance(exception, commands.NoPrivateMessage): return elif isinstance(exception, commands.DisabledCommand): return elif isinstance(exception, commands.CommandInvokeError): payload = { "embeds": [ { "title": f"Command: {ctx.command.qualified_name}, Instance: {self.bot.instance}", "description": f"```py\n{exception}\n```\n By `{ctx.author}` (`{ctx.author.id}`)", "color": 16740159 } ] } async with aiohttp.ClientSession() as cs: await cs.post(self.webhook_url, json=payload) em = discord.Embed(color=0xDEADBF, title="Error", description=f"Error in command {ctx.command.qualified_name}, " f"[Support Server](https://discord.gg/q98qeYN).\n`{exception}`") await ctx.send(embed=em) log.warning('In {}:'.format(ctx.command.qualified_name)) log.warning('{}: {}'.format(exception.original.__class__.__name__, exception.original)) traceback.print_exc(file=sys.stdout) elif isinstance(exception, commands.BadArgument): await self.send_cmd_help(ctx) elif isinstance(exception, commands.MissingRequiredArgument): await self.send_cmd_help(ctx) elif isinstance(exception, commands.CheckFailure): _ = await self._get_text(ctx) await ctx.send(_('You are not allowed to use that command.'), delete_after=5) elif isinstance(exception, commands.CommandOnCooldown): _ = await self._get_text(ctx) await ctx.send(_('Command is on cooldown... {:.2f}s left').format(exception.retry_after), delete_after=5) elif isinstance(exception, commands.CommandNotFound): return else: return
def __init__(self, **kwargs): intents = discord.Intents(guilds=True, members=True, emojis=True, voice_states=True, messages=True, reactions=True) super().__init__( command_prefix=_prefix_pred, help_command=util.BloodyHelpCommand(), owner_id=529535587728752644, case_insensitive=True, allowed_mentions=discord.AllowedMentions(everyone=False, roles=False, users=True), status=discord.Status.online, activity=discord.Game( f"https://bitchbot.31416.dev | >help | >invite"), intents=intents, member_cache_flags=discord.MemberCacheFlags.from_intents(intents)) self.loop = self.loop or asyncio.get_event_loop() self.session = aiohttp.ClientSession() self.quart_app = QuartWithBot(__name__, static_folder=None) self.quart_app.debug = keys.debug config = { "DEBUG": keys.debug, "CACHE_TYPE": "simple", "CACHE_DEFAULT_TIMEOUT": 300 } self.quart_app.config.from_mapping(config) Cache(self.quart_app) # Probably should put it with config self.initial_cogs = kwargs.pop('cogs') # socket stats props self.socket_stats = {} self.lines_of_code_count = self._count_lines_of_code() self.prefixes = {} self.blacklist = {} self.blacklist_message_bucket = commands.CooldownMapping.from_cooldown( 1, 15.0, commands.BucketType.user) self.log_webhook = discord.Webhook.from_url( keys.logWebhook, adapter=discord.AsyncWebhookAdapter(self.session)) self._before_invoke = before_invoke self._after_invoke = after_invoke self.add_check(global_check)
async def get_webhook_if_possible(bot: 'MyBot', channel: discord.TextChannel): db_channel: DiscordChannel = await get_from_db(channel) if len(db_channel.webhook_urls) == 0: webhook = await create_and_save_webhook(bot, channel) else: webhook = discord.Webhook.from_url( random.choice(db_channel.webhook_urls), adapter=discord.AsyncWebhookAdapter(bot.client_session)) return webhook
async def on_guild_remove(self, guild): bots = [member for member in guild.members if member.bot] async with aiohttp.ClientSession() as session: webhook = discord.Webhook.from_url( webhook_url, adapter=discord.AsyncWebhookAdapter(session)) await webhook.send(content=':outbox_tray: **Guild Removed** `' + guild.name.strip('`') + '` (`' + str(guild.id) + '`)\n Total: **' + str(guild.member_count) + '** | Users: **' + str(guild.member_count - len(bots)) + '** | Bots: **' + str(len(bots)) + '**')
async def on_disconnect(self): """Ping a given webhook when the bot is disconnected""" if self.bot.config.get("event_webhook_url"): webhook = discord.Webhook.from_url( self.bot.config['event_webhook_url'], adapter=discord.AsyncWebhookAdapter(self.bot.session)) await webhook.send( f"Bot disconnect event just pinged for instance with shards `{self.bot.shard_ids}` - {dt.utcnow().strftime('%X.%f')}", username=f"{self.bot.user.name} - Disconnect") self.logger.info("Sent webhook for on_disconnect event")
async def on_shard_ready(self, shard_id: int): """Ping a given webhook when the shard ID becomes ready""" if self.bot.config.get("event_webhook_url"): webhook = discord.Webhook.from_url( self.bot.config['event_webhook_url'], adapter=discord.AsyncWebhookAdapter(self.bot.session)) await webhook.send( f"Shard ready event just pinged for shard ID `{shard_id}` - {dt.utcnow().strftime('%X.%f')}", username=f"{self.bot.user.name} - Shard Ready") self.logger.info( f"Sent webhook for on_shard_ready event in shard `{shard_id}`")
async def on_error(self, event_method, *args, **kwargs): exc = traceback.format_exc() logger.error(f"Ignoring exception in {event_method}:\n{exc}") hook = discord.Webhook.from_url(auth.WEBHOOKS['errors'], adapter=discord.AsyncWebhookAdapter( self.session)) try: await hook.send( f"Exception occurred in {event_method}: ```py\n{exc[:1850]}\n```" ) except discord.DiscordException: logger.error("Failed to log error to logging channel.")
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._BotBase__cogs = commands.core._CaseInsensitiveDict() # Base variables for core functionality with open("config.toml") as f: self.settings = toml.loads(f.read()) self.session = aiohttp.ClientSession() self.embed_color = 0x89CFF0 self.support_invite = self.settings["misc"]["support_server_invite"] self.invite = self.settings["misc"]["invite"] # Cache so I don't have to use DB self.prefixes = collections.defaultdict(list) self.default_prefix = "p!" self.command_list = [] self.afk = {} self.highlights = {} self.blacklist = {} self.usage_counter = 0 self.command_usage = collections.Counter() # Webhooks self.error_webhook = discord.Webhook.from_url( self.settings["misc"]["error_webhook"], adapter=discord.AsyncWebhookAdapter(self.session), ) self.guild_webhook = discord.Webhook.from_url( self.settings["misc"]["guild_webhook"], adapter=discord.AsyncWebhookAdapter(self.session), ) # API stuff self.alex = alexflipnote.Client(self.settings["keys"]["alexflipnote"]) self.perspective = self.settings["keys"]["perspective"] # Bot management self.maintenance = False self.context = commands.Context
async def send(url, msg): async with aiohttp.ClientSession() as session: try: webhook = discord.Webhook.from_url( url, adapter=discord.AsyncWebhookAdapter(session)) await webhook.send(msg, username="******", avatar_url=bot.user.avatar_url) await ctx.send(embed=embedsuccess("Sended")) except: await ctx.send(embed=embederror( "Not a valid webhook URL \n `Usage: <webhookurl>, <message>`" ))
async def on_shard_ready(self, shard_id: int): ws = json.loads( self.bot._connection._get_websocket(shard_id=shard_id)._trace[0]) em = discord.Embed(color=self.bot.color) em.description = f"**Gateway server:** {ws[0]}\n**Session server:** {ws[1]['calls'][0]}" em.set_author(name=f"Shard {shard_id} ready") webhook = discord.Webhook.from_url(os.getenv("READY"), adapter=discord.AsyncWebhookAdapter( self.bot.session)) await webhook.send(embed=em, username="******", avatar_url=self.bot.user.avatar_url)
async def edit_msg(self, source_message: discord.Message, dest_message: Union[discord.WebhookMessage, discord.Message]): guild = dest_message.guild data = await self.config.guild(guild).all() channel = self.bot.get_channel( data['channel']) if data['channel'] else None if not channel: raise ChannelUnavailable('Salon textuel non disponible') try: msg_data = await self.config.guild(guild).cache.get_raw( source_message.id) except: raise NoMsgData( "Le message fourni n'a pas de données enregistrées") votes = len(msg_data["votes"]) emoji = self.decode_emoji(data['emoji']) foot = f"{emoji} {votes}" if type( emoji) is str else f"{emoji.name} {votes}" em = dest_message.embeds[0] em.set_footer(text=foot) if data['webhook_url']: try: async with aiohttp.ClientSession() as session: webhook = discord.Webhook.from_url( data['webhook_url'], adapter=discord.AsyncWebhookAdapter(session)) return await webhook.edit_message(dest_message.id, embed=em) except: logger.info( f"Suppression des données de {source_message.id} car impossibilité définitive d'accéder à MSG_ID={dest_message.id} " f"(message probablement supprimé)") await self.config.guild(guild).favs.clear_raw(source_message.id ) raise else: try: return await dest_message.edit(embed=em) except discord.Forbidden: logger.info(f"Impossible d'accéder à MSG_ID={dest_message.id}") except: logger.info( f"Suppression des données de {source_message.id} car impossibilité définitive d'accéder à MSG_ID={dest_message.id} " f"(message probablement supprimé)") await self.config.guild(guild).favs.clear_raw(source_message.id ) raise
async def send_webhook(self, text: str, username: str, logger: str) -> bool: """ Send a webhook to the bot specified event webhook url. """ if not self.bot.config.get("event_webhook_url"): return False webhook = discord.Webhook.from_url( self.bot.config['event_webhook_url'], adapter=discord.AsyncWebhookAdapter(self.bot.session)) await webhook.send(text, username=username) self.logger.info(logger) return True
async def webhook_send( url, message, username="******", avatar="https://raw.githubusercontent.com/AakashSharma7269/erin/main/erin.png?token=AOP54YUJCVK5WQY5LQ6AK5TAWOXYK", ): async with aiohttp.ClientSession() as session: webhook = discord.Webhook.from_url( url, adapter=discord.AsyncWebhookAdapter(session)) if isinstance(message, discord.Embed): await webhook.send(embed=message, username=username, avatar_url=avatar) else: await webhook.send(message, username=username, avatar_url=avatar)
async def unregister(self, ctx: commands.Context): ''' グローバルチャットの登録を解除します ''' guild = await q.Guild(self.bot, ctx.guild.id).get() if guild.gc_channel is None: await ctx.send(f"グローバルチャットサービスはまだ利用していません") else: async with aiohttp.ClientSession() as session: hook = discord.Webhook.from_url( guild.gc_url, adapter=discord.AsyncWebhookAdapter(session)) await q.Guild(self.bot, ctx.guild.id).set(gc_channel=None, gc_url=None) await ctx.send(f"グローバルチャットサービスの利用を終了しました") await hook.delete()
def get_event_webhook(self, event_name:str) -> typing.Optional[discord.Webhook]: """ Wowie it's time for webhooks """ # First we're gonna use the legacy way of event webhooking, which is to say: it's just in the config url = self.config.get("event_webhook_url") if url: try: self.logger.debug("Grabbed event webhook from config") return discord.Webhook.from_url(url, adapter=discord.AsyncWebhookAdapter(self.session)) except discord.InvalidArgument: self.logger.error("The webhook set in your config is not a valid Discord webhook") return None if url is not None: return # Now we're gonna do with the new handler webhook_picker = self.config.get("event_webhook") if webhook_picker is None: return None # See if the event is enabled new_url = webhook_picker.get("events", dict()).get(event_name) if new_url in ["", None, False]: return None if isinstance(new_url, str): url = new_url else: url = webhook_picker.get("event_webhook_url", "") try: self.logger.debug(f"Grabbed event webhook for event {event_name} from config") return discord.Webhook.from_url(url, adapter=discord.AsyncWebhookAdapter(self.session)) except discord.InvalidArgument: self.logger.error(f"The webhook set in your config for the event {event_name} is not a valid Discord webhook") return None
async def on_ready(): embed = discord.Embed( title=f'Bot Started At:\n{datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d %H:%M")} UTC', color=0x00FF00, timestamp=datetime.datetime.now(datetime.timezone.utc), ) async with aiohttp.ClientSession() as s: webhook = discord.Webhook.from_url( f"https://discordapp.com/api/webhooks/{hookChannel}/{hookToken}", adapter=discord.AsyncWebhookAdapter(s), ) await webhook.send(embed=embed) print("Bot is ready") # message which bot sends when it is ready
async def on_command_error(ctx, error): if isinstance(error, commands.CommandNotFound): await ctx.send( 'Invalid command. Please use `$help` to know list current valid commands.' ) else: embed = discord.Embed(title='Unhandled Exception Thrown', color=0xFF0000) exception_text = ''.join( traceback.format_exception(error, error, error.__traceback__)) exception_text = exception_text[ 0:exception_text.find('The above exception was')].strip() print(exception_text, file=sys.stderr) try: chan_name = ctx.channel.name except: chan_name = 'DMChannel' name = 'Message Details:' value = f'[Jump to message]({ctx.message.jump_url})' value += f'```\nChannel: #{chan_name}\n' value += f'Author: {ctx.message.author}\n' value += f'Message: {ctx.message.content}\n```' embed.add_field(name=name, value=value, inline=False) field_len = 1000 fields = [ exception_text[i:i + field_len] for i in range(0, len(exception_text), field_len) ] for i, field in enumerate(fields): f_name = 'Traceback:' if i == 0 else 'Continued:' embed.add_field(name=f_name, value=f'```{field}```', inline=False) async with aiohttp.ClientSession() as s: webhook = discord.Webhook.from_url( f'https://discordapp.com/api/webhooks/{hookChannel}/{hookToken}', adapter=discord.AsyncWebhookAdapter(s)) await webhook.send(embed=embed) await ctx.send( f'An error occurred. Please use `{bot.command_prefix}reportbot <Error>`' )
async def dagpi_delete(self, ctx): msg = await ctx.send("Are you SURE you want to DELETE Automeme") await msg.add_reaction('<a:giftick:734746863340748892>') # and reaction.author != ctx.author def check(reaction, user): # print('reaction') return reaction.message.id == msg.id and not user.bot and \ user.id == ctx.author.id and \ str(reaction.emoji) == '<a:giftick:734746863340748892>' try: reaction, user = await self.bot.wait_for('reaction_add', check=check, timeout=60.0) except asyncio.TimeoutError: return await ctx.send('No response recieved aborting deleteion ') else: await ctx.send("Deleteing Automemer") async with self.bot.pool.acquire() as connection: async with connection.transaction(): query = """ SELECT * FROM automeme WHERE server_id = $1; """ data = await connection.fetch(query, ctx.guild.id) try: adap = discord.AsyncWebhookAdapter(self.bot.session) hook = discord.Webhook.from_url(data[0]["webhook_url"], adapter=adap) except KeyError or IndexError: return await ctx.send( "Could not find a automemer for this" "server. Please setup one first") del_query = """ DELETE FROM automeme WHERE server_id = $1; """ await connection.execute(del_query, ctx.guild.id) await self.bot.caching.automemecache() try: await hook.delete(reason="Automemer Deletion") return await ctx.send("Deleted the Webook") except discord.Forbidden or discord.HTTPException: return await ctx.send("Deleted webhok from database." "Can not delete webhook from discord" "Plase manually delete the webhook" "Error due to missing perms")
async def get_context_from_interaction(self, payload, *, cls=utils.interactions. InteractionContext): # Make a context view = commands.view.StringView( f"<@{self.bot.user.id}> {payload['data']['name']} {' '.join([i['value'] for i in payload['data'].get('options', list())])}" ) fake_message = utils.interactions.InteractionMessage( guild=self.bot.get_guild(int(payload['guild_id'])), channel=self.bot.get_channel(int(payload['channel_id'])), author=self.bot.get_guild(int(payload['guild_id'])).get_member( int(payload['member']['user']['id'])), state=self.bot._get_state(), data=payload, content=view.buffer, ) ctx = cls(prefix=f"<@{self.bot.user.id}> ", view=view, bot=self.bot, message=fake_message) ctx.is_slash_command = True ctx.original_author_id = int(payload['member']['user']['id']) view.skip_string(f"<@{self.bot.user.id}> ") invoker = view.get_word() # Make it work ctx.invoked_with = invoker ctx._interaction_webhook = discord.Webhook.partial( await self.bot.get_application_id(), payload["token"], adapter=discord.AsyncWebhookAdapter(self.bot.session)) ctx.command = self.bot.all_commands.get(invoker) # Send async data response self.logger.debug( "Posting type 5 response for interaction command %s." % (str(payload))) url = "https://discord.com/api/v8/interactions/{id}/{token}/callback".format( id=payload["id"], token=payload["token"]) await self.bot.session.post( url, json={"type": 5}, headers={"Authorization": f"Bot {self.bot.config['token']}"}) # Return context return ctx
async def report(self, context, *, message: str = ""): if not message: await context.send("Nem adtál meg üzenetet.") return # TODO: Read the webhook url from config url = "" if not url: await context.send("Report parancs jelenleg nem elérhető.") return async with aiohttp.ClientSession() as session: webhook = discord.Webhook.from_url( url, adapter=discord.AsyncWebhookAdapter(session)) await webhook.send(message) await context.send("Köszönjük jelentésed!")
async def log(ctx, msg, sent_message, out=None): embed = discord.Embed(color=random_discord_color(), description=msg) embed.set_author(name=f"{ctx.author.name}#{ctx.author.discriminator}", icon_url=ctx.author.avatar_url) embed.timestamp = ctx.message.created_at if out: embed.add_field(name="Output:", value=out, inline=False) embed.add_field(name='Message', value=f'[Jump To Message]({sent_message.jump_url})') webhook = discord.Webhook.from_url(keys.logWebhook, adapter=discord.AsyncWebhookAdapter( ctx.bot.session)) await webhook.send(embed=embed, username=ctx.command.name)