Skip to content

Commit

Permalink
ClashKing v4
Browse files Browse the repository at this point in the history
  • Loading branch information
MagicTheDev committed Jan 29, 2024
1 parent 952fd20 commit 0981a44
Show file tree
Hide file tree
Showing 5 changed files with 56 additions and 49 deletions.
23 changes: 11 additions & 12 deletions classes/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import coc
import motor.motor_asyncio
import disnake
import pytz
import os
import re
import asyncio
Expand All @@ -13,12 +12,12 @@
import aiohttp
import emoji
import expiring_dict
import pendulum as pend

from math import ceil
from datetime import datetime, timedelta
from coc.ext import discordlinks
from disnake.ext import commands
from dotenv import load_dotenv
from typing import Dict, List
from assets.emojiDictionary import emojiDictionary, legend_emojis
from classes.player import MyCustomPlayer, CustomClanClass
Expand All @@ -30,16 +29,16 @@
from expiring_dict import ExpiringDict
from redis import asyncio as redis
from classes.DatabaseClient.familyclient import FamilyClient
utc = pytz.utc
load_dotenv()

from classes.config import Config
from apscheduler.schedulers.asyncio import AsyncIOScheduler


class CustomClient(commands.AutoShardedBot):
def __init__(self, **options):
super().__init__(**options)
def __init__(self, config: Config, command_prefix: str, help_command, intents: disnake.Intents, scheduler: AsyncIOScheduler):
super().__init__(command_prefix=command_prefix, help_command=help_command, intents=intents)

self.__config: dict = options.pop("config", None)
self._config = config
self.scheduler = scheduler
self.ck_client: FamilyClient = None

self.looper_db = motor.motor_asyncio.AsyncIOMotorClient(os.getenv("LOOPER_DB_LOGIN"))
Expand Down Expand Up @@ -250,7 +249,7 @@ async def get_tags(self, ping):
return tags

def gen_raid_date(self):
now = datetime.utcnow().replace(tzinfo=utc)
now = datetime.utcnow().replace(tzinfo=pend.UTC)
current_dayofweek = now.weekday()
if (current_dayofweek == 4 and now.hour >= 7) or (current_dayofweek == 5) or (current_dayofweek == 6) or (
current_dayofweek == 0 and now.hour < 7):
Expand All @@ -267,15 +266,15 @@ def gen_raid_date(self):

def gen_season_date(self, seasons_ago = None, as_text=True):
if seasons_ago is None:
end = coc.utils.get_season_end().replace(tzinfo=utc).date()
end = coc.utils.get_season_end().replace(tzinfo=pend.UTC).date()
month = end.month
if end.month <= 9:
month = f"0{month}"
return f"{end.year}-{month}"
else:
dates = []
for x in range(0, seasons_ago + 1):
end = coc.utils.get_season_end().replace(tzinfo=utc) - dateutil.relativedelta.relativedelta(months=x)
end = coc.utils.get_season_end().replace(tzinfo=pend.UTC) - dateutil.relativedelta.relativedelta(months=x)
if as_text:
dates.append(f"{calendar.month_name[end.date().month]} {end.date().year}")
else:
Expand All @@ -294,7 +293,7 @@ def gen_games_season(self):
return f"{now.year}-{month}"

def gen_previous_season_date(self):
end = coc.utils.get_season_start().replace(tzinfo=utc).date()
end = coc.utils.get_season_start().replace(tzinfo=pend.UTC).date()
month = end.month
if end.month <= 9:
month = f"0{month}"
Expand Down
25 changes: 25 additions & 0 deletions classes/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from os import getenv
from dotenv import load_dotenv
from dataclasses import dataclass
load_dotenv()

@dataclass(frozen=True, slots=True)
class Config:
coc_email = getenv("COC_EMAIL")
coc_password = getenv("COC_PASSWORD")
static_mongodb = getenv("STATIC_MONGODB")
stats_mongodb = getenv("STATS_MONGODB")
link_api_username = getenv("LINK_API_USER")
link_api_password = getenv("LINK_API_PW")
bot_token = getenv("BOT_TOKEN")
sentry_dsn = getenv("SENTRY_DSN")
redis_ip = getenv("REDIS_IP")
redis_pw = getenv("REDIS_PW")
bunny_api_token = getenv("BUNNY_ACCESS_KEY")
portainer_ip = getenv("PORTAINER_IP")
portainer_api_token = getenv("PORTAINER_API_TOKEN")
reddit_user_secret = getenv("REDDIT_SECRET")
reddit_user_password = getenv("REDDIT_PW")
open_ai_api_token = getenv("OPENAI_API_KEY")
is_beta = (getenv("IS_BETA") == "TRUE")
is_custom = (getenv("IS_CUSTOM") == "TRUE")
3 changes: 3 additions & 0 deletions example.env
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ LINK_API_USER = discord_links_user
LINK_API_PW = dicord_links_pw

BOT_TOKEN = bot_token
IS_BETA = TRUE
IS_CUSTOM = TRUE

SENTRY_DSN = sentry_stats_token

Expand All @@ -18,6 +20,7 @@ REDIS_PW = redis_db_pw

BUNNY_ACCESS_KEY = bunny.net_access_token

PORTAINER_IP = 0.0.0.0
PORTAINER_API_TOKEN = portainer_api_token

REDDIT_SECRET = reddit_user_secret
Expand Down
53 changes: 17 additions & 36 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,8 @@
import motor.motor_asyncio
import sentry_sdk
from classes.bot import CustomClient
from disnake import Client
from disnake.ext import commands
import argparse
import json
from types import SimpleNamespace
#data = json.load(open(f"hidden_config.json"))

# Parse JSON into an object with attributes corresponding to dict keys.
#x = json.loads(data, object_hook=lambda d: SimpleNamespace(**d))
from classes.config import Config

from apscheduler.schedulers.asyncio import AsyncIOScheduler
from pytz import utc
Expand All @@ -21,30 +14,16 @@
scheduler = AsyncIOScheduler(timezone=utc)
scheduler.start()

config = Config()
intents = disnake.Intents(
guilds=True,
members=True,
emojis=True,
messages=True,
message_content=True
)

parser = argparse.ArgumentParser(description="Just an example", formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("-c", "--custom", action="store_true", help="custom mode")
parser.add_argument("-b", "--beta", action="store_true", help="beta mode")
parser.add_argument("-k", "--test", action="store_true", help="test mode")
parser.add_argument("-t", "--token", help="token")

args = parser.parse_args()
config = vars(args)

IS_BETA = config.get("beta", False)
IS_CUSTOM = config.get("custom", False)
IS_TEST = config.get("test", False)
TOKEN = config.get("token")

discClient = Client()
intents = disnake.Intents().none()
intents.guilds = True
intents.members = True
intents.emojis = True
intents.messages = True
intents.message_content = True

bot = CustomClient(command_prefix="??",help_command=None, intents=intents)
bot = CustomClient(command_prefix="??", help_command=None, intents=intents, scheduler=scheduler, config=config)

def check_commands():
async def predicate(ctx: disnake.ApplicationCommandInteraction):
Expand Down Expand Up @@ -99,7 +78,8 @@ async def predicate(ctx: disnake.ApplicationCommandInteraction):
]

disallowed = set()
if IS_CUSTOM:

if config.is_custom:
disallowed.add("owner")

def load():
Expand All @@ -115,7 +95,7 @@ def load():


#dont let custom or local run
if not IS_BETA and not IS_CUSTOM:
if not config.is_beta and not config.is_custom:
initial_extensions += [
"Background.reddit_recruit_feed",
"Background.region_lb_update"
Expand All @@ -127,7 +107,7 @@ def load():
]

#only the local version can not run
if not IS_TEST:
if not config.is_beta:
initial_extensions += [
"Background.voicestat_loop",
"Background.Logs.auto_eval",
Expand Down Expand Up @@ -164,13 +144,14 @@ def before_send(event, hint):
before_send=before_send
)
load()
print(initial_extensions)
for extension in initial_extensions:
try:
bot.load_extension(extension)
except Exception as extension:
traceback.print_exc()

if not IS_BETA:
if not config.is_beta:
bot.loop.create_task(kafka_events())

bot.run(TOKEN)
bot.run(config.bot_token)
1 change: 0 additions & 1 deletion utility/components.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
from utility.constants import BOARD_TYPES
from typing import Union

bot = CustomClient()

def create_components(current_page, embeds, print=False):
length = len(embeds)
Expand Down

0 comments on commit 0981a44

Please sign in to comment.