-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
launcher.py
119 lines (92 loc) · 4.17 KB
/
launcher.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# launcher.py
from bot.bot import LeagueBot
import argparse
import asyncio
import asyncpg
import discord
from dotenv import load_dotenv
import json
import logging
import os
ABS_ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
EMOJI_FILE = os.path.join(ABS_ROOT_DIR, 'emojis.json')
BOT_LOGGER = logging.getLogger('csgoleague.bot')
load_dotenv() # Load the environment variables in the local .env file
if os.name == 'nt':
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
def _get_loop():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
return loop
def run_bot():
""" Parse the config file and run the bot. """
# Get database pool for bot
db_connect_url = 'postgresql://{POSTGRESQL_USER}:{POSTGRESQL_PASSWORD}@{POSTGRESQL_HOST}/{POSTGRESQL_DB}'
db_pool = _get_loop().run_until_complete(asyncpg.create_pool(db_connect_url.format(**os.environ)))
# Check API URL
api_url = os.environ['CSGO_LEAGUE_API_URL']
if api_url.endswith('/'):
api_url = api_url[:-1]
# Get emojis
with open(EMOJI_FILE) as f:
emoji_dict = json.load(f)
# Run bot
bot = LeagueBot(os.environ['DISCORD_BOT_TOKEN'], api_url, os.environ['CSGO_LEAGUE_API_KEY'], db_pool, emoji_dict)
bot.run()
def create_emojis(guild_id):
""""""
client = discord.Client(loop=_get_loop())
@client.event
async def on_ready():
""""""
guild = await client.fetch_guild(guild_id)
icon_dir = os.path.join(ABS_ROOT_DIR, 'assets', 'maps', 'icons')
reason = 'Used by the CS:GO League Bot'
existing_emojis = {emoji.name: emoji for emoji in guild.emojis}
if os.path.exists(EMOJI_FILE):
with open(EMOJI_FILE) as f:
emoji_dict = json.load(f)
else:
emoji_dict = {}
for item in os.listdir(icon_dir):
if item.endswith('.png'):
emoji_name = item.split('.')[0] # Remove file extension for emoji name
# Check if emoji already exists and if it was made by this bot
if emoji_name in existing_emojis:
# Emoji user attribute only accessible with fetch_emoji()
existing_emoji = await guild.fetch_emoji(existing_emojis[emoji_name].id)
if existing_emoji.user == client.user:
BOT_LOGGER.info(
f'Emoji :{existing_emoji.name}: has already been created in the server, updating'
)
emoji_dict[existing_emoji.name] = f'<:{existing_emoji.name}:{existing_emoji.id}>'
continue
# Attempt to create emoji
try:
with open(os.path.join(icon_dir, item), 'rb') as file:
new_emoji = await guild.create_custom_emoji(name=emoji_name, image=file.read(), reason=reason)
except discord.Forbidden:
BOT_LOGGER.error('Bot does not have permission to create custom emojis in the specified server')
break
except discord.HTTPException as e:
BOT_LOGGER.error(f'HTTP exception raised when creating emoji for "{item}": {e.text} ({e.code})')
except Exception as e:
BOT_LOGGER.error(f'Exception {e} occurred')
else:
BOT_LOGGER.info(f'Emoji :{emoji_name}: created successfully')
emoji_dict[new_emoji.name] = f'<:{new_emoji.name}:{new_emoji.id}>'
with open(EMOJI_FILE, 'w+') as f:
json.dump(emoji_dict, f)
await client.close()
# Run the client with the token in the local .env file
load_dotenv()
client.run(os.environ['DISCORD_BOT_TOKEN'])
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Run the CS:GO League bot')
parser.add_argument('-e', '--emojis', type=int, required=False, metavar='serverID',
help='create necessary bot emojis in the specified server and save the info to a JSON file')
args = parser.parse_args()
if args.emojis:
guild_id = args.emojis
create_emojis(guild_id)
run_bot()