Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 52 additions & 51 deletions bot.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import asyncio
import datetime
import coc
import discord
import aiohttp
import traceback
import creds
Expand All @@ -12,10 +10,12 @@
import json

import asyncpg
import coc
import disnake
import sentry_sdk

from coc.ext import discordlinks
from discord.ext import commands
from disnake.ext import commands

from botlog import setup_logging, add_hooks
from cogs.utils import context
Expand Down Expand Up @@ -69,13 +69,7 @@
links_client = discordlinks.login(creds.links_username, creds.links_password)

description = "A simple discord bot to track donations of clan families in clash of clans."
intents = discord.Intents.none()
intents.guilds = True
intents.guild_messages = True
intents.guild_reactions = True
intents.members = True
intents.emojis = True

intents = disnake.Intents(guilds=True, guild_messages=True, guild_reactions=True, members=True, emojis=True)

log = logging.getLogger()

Expand Down Expand Up @@ -107,13 +101,13 @@ async def init(con):

class DonationBot(commands.AutoShardedBot):
def __init__(self):
super().__init__(command_prefix=get_pref, case_insensitive=True,
description=description, pm_help=None, help_attrs=dict(hidden=True),
intents=intents, chunk_guilds_at_startup=False, allowed_mentions=discord.AllowedMentions.none())
super().__init__(command_prefix="!", intents=intents, chunk_guilds_at_startup=False,
allowed_mentions=disnake.AllowedMentions.none(),
test_guilds=[594276321937326091], sync_commands_debug=True)

self.prefixes = dict()

self.colour = discord.Colour.blurple()
self.colour = disnake.Colour.blurple()

self.coc = coc_client
self.links = links_client
Expand All @@ -125,8 +119,8 @@ def __init__(self):
self.session = aiohttp.ClientSession(loop=self.loop)

add_hooks(self)
self.before_invoke(self.before_command_invoke)
self.after_invoke(self.after_command_invoke)
# self.before_invoke(self.before_command_invoke)
# self.after_invoke(self.after_command_invoke)

self.uptime = datetime.datetime.utcnow()

Expand Down Expand Up @@ -156,45 +150,52 @@ def utils(self):
def background(self):
return self.get_cog('BackgroundManagement')

async def before_command_invoke(self, ctx):
if hasattr(ctx, 'before_invoke'):
await ctx.before_invoke(ctx)

async def after_command_invoke(self, ctx):
if hasattr(ctx, 'after_invoke'):
await ctx.after_invoke(ctx)

async def on_message(self, message):
if message.author.bot:
return # ignore bot messages

await self.process_commands(message)

async def process_commands(self, message):
# we have a couple attributes to add to context, lets add them now (easy db connection etc.)
ctx = await self.get_context(message, cls=context.Context)

if ctx.guild is None:
invite = getattr(self, "invite", discord.utils.oauth_url(self.user.id))
return await ctx.send(f"Please invite me to a server to run commands: {invite}")

if ctx.command is None:
if self.user in message.mentions and message.channel.permissions_for(ctx.me).send_messages:
await ctx.send(f"My prefix for this guild is {self.prefixes.get(message.guild.id, '+')}")

return # if there's no command invoked return

async with ctx.acquire():
await self.invoke(ctx)
# async def before_command_invoke(self, ctx):
# if hasattr(ctx, 'before_invoke'):
# await ctx.before_invoke(ctx)
#
# async def after_command_invoke(self, ctx):
# if hasattr(ctx, 'after_invoke'):
# await ctx.after_invoke(ctx)

# async def on_message(self, message):
# if message.author.bot:
# return # ignore bot messages
#
# await self.process_commands(message)

async def process_application_commands(self, interaction):
log.info("Received interaction command %s", str(interaction))
await interaction.response.defer()
async with self.pool.acquire(timeout=60.0) as conn:
interaction.db = conn
await super().process_application_commands(interaction)
#
# async def process_commands(self, message):
# # we have a couple attributes to add to context, lets add them now (easy db connection etc.)
# ctx = await self.get_context(message, cls=context.Context)
#
# if ctx.guild is None:
# invite = getattr(self, "invite", discord.utils.oauth_url(self.user.id))
# return await ctx.send(f"Please invite me to a server to run commands: {invite}")
#
# if ctx.command is None:
# if self.user in message.mentions and message.channel.permissions_for(ctx.me).send_messages:
# await ctx.send(f"My prefix for this guild is {self.prefixes.get(message.guild.id, '+')}")
#
# return # if there's no command invoked return
#
# async with ctx.acquire():
# await self.invoke(ctx)

async def on_ready(self):
await self.change_presence(activity=discord.Game('+help for commands'))
# await self.change_presence(activity=discord.Game('+help for commands'))
await self.init_prefixes()
self.error_webhooks = itertools.cycle(n for n in await self.get_channel(625160612791451661).webhooks())
self.fake_clan_guilds = {row['guild_id'] for row in await self.pool.fetch("SELECT DISTINCT guild_id FROM clans WHERE fake_clan=True")}

async def on_resumed(self):
await self.change_presence(activity=discord.Game('+help for commands'))
# async def on_resumed(self):
# await self.change_presence(activity=discord.Game('+help for commands'))

async def get_clans(self, guild_id, in_event=False):
if in_event:
Expand Down Expand Up @@ -241,7 +242,7 @@ async def query_member_by_id_batch(self, guild, user_ids, only_guild=True):
for user_id in to_fetch:
try:
member = await guild.fetch_member(user_id)
except discord.HTTPException:
except disnake.HTTPException:
pass
else:
results.append(member)
Expand Down Expand Up @@ -278,7 +279,7 @@ async def query_member_by_id_batch(self, guild, user_ids, only_guild=True):
for user_id in to_fetch:
try:
user = await self.fetch_user(user_id)
except discord.HTTPException:
except disnake.HTTPException:
pass
else:
results.append(user)
Expand Down
67 changes: 25 additions & 42 deletions botlog.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,30 @@
import asyncio
import creds
import discord
import disnake
import logging
import logging.handlers
import math
import itertools
import sys
from google.cloud import logging as glogging
from oauth2client.service_account import ServiceAccountCredentials

def setup_logging(bot, test_syncer=False):
google_log_client = glogging.Client(project='donationbot')
google_log_client.setup_logging()

bot.message_log = google_log_client.logger('messages')
# from google.cloud import logging as glogging
# from oauth2client.service_account import ServiceAccountCredentials

bot.command_log = google_log_client.logger('commands')
bot.guild_log = google_log_client.logger('guilds')
bot.clan_log = google_log_client.logger('clans')
bot.google_logger = google_log_client.logger('syncer')
bot.board_log = google_log_client.logger('boards')
def setup_logging(bot, test_syncer=False):
# google_log_client = glogging.Client(project='donationbot')
# google_log_client.setup_logging()

logging.getLogger('discord').setLevel(logging.INFO)
logging.getLogger('discord.http').setLevel(logging.WARNING)
logging.getLogger('discord.state').setLevel(logging.WARNING)
# bot.message_log = google_log_client.logger('messages')
#
# bot.command_log = google_log_client.logger('commands')
# bot.guild_log = google_log_client.logger('guilds')
# bot.clan_log = google_log_client.logger('clans')
# bot.google_logger = google_log_client.logger('syncer')
# bot.board_log = google_log_client.logger('boards')

logging.getLogger('disnake').setLevel(logging.INFO)
logging.getLogger('disnake.http').setLevel(logging.WARNING)
logging.getLogger('disnake.state').setLevel(logging.WARNING)
logging.getLogger('websockets.protocol').setLevel(logging.WARNING)
logging.getLogger('coc').setLevel(logging.INFO)
logging.getLogger('coc.events').setLevel(logging.INFO)
Expand All @@ -44,11 +45,9 @@ def setup_logging(bot, test_syncer=False):
stream_handler.setFormatter(fmt)
log.addHandler(stream_handler)

bot.error_webhooks = itertools.cycle([discord.Webhook.partial(
id=creds.log_hook_id,
token=creds.log_hook_token,
adapter=discord.AsyncWebhookAdapter(session=bot.session)
)])
bot.error_webhooks = itertools.cycle(
[disnake.Webhook.partial(id=creds.log_hook_id, token=creds.log_hook_token, session=bot.session)]
)
# add handler to the logger
# handler = logging.handlers.SysLogHandler('/dev/log')
#
Expand Down Expand Up @@ -101,27 +100,11 @@ def emit(self, record):


def add_hooks(bot):
bot.error_webhook = discord.Webhook.partial(id=creds.error_hook_id,
token=creds.error_hook_token,
adapter=discord.AsyncWebhookAdapter(
session=bot.session)
)
bot.join_log_webhook = discord.Webhook.partial(id=creds.join_log_hook_id,
token=creds.join_log_hook_token,
adapter=discord.AsyncWebhookAdapter(
session=bot.session)
)
bot.feedback_webhook = discord.Webhook.partial(id=creds.feedback_hook_id,
token=creds.feedback_hook_token,
adapter=discord.AsyncWebhookAdapter(
session=bot.session)
)
bot.command_webhook = discord.Webhook.partial(id=creds.command_hook_id,
token=creds.command_hook_token,
adapter=discord.AsyncWebhookAdapter(
session=bot.session
)
)
bot.error_webhook = disnake.Webhook.partial(id=creds.error_hook_id, token=creds.error_hook_token, session=bot.session)
bot.join_log_webhook = disnake.Webhook.partial(id=creds.join_log_hook_id, token=creds.join_log_hook_token, session=bot.session)
bot.feedback_webhook = disnake.Webhook.partial(id=creds.feedback_hook_id, token=creds.feedback_hook_token, session=bot.session)
bot.command_webhook = disnake.Webhook.partial(id=creds.command_hook_id, token=creds.command_hook_token, session=bot.session)

return bot


Loading