-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgmas_bot.py
166 lines (140 loc) · 4.97 KB
/
gmas_bot.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
import random
import asyncio
from random import randint
import json
import os
import discord
from discord.ext import commands, tasks
from discord import Game
from discord.ext.commands import Bot
from discord.ext.tasks import loop
import backgroundTasks
from time import sleep
import pytz
import asyncio
from datetime import datetime
from json import JSONEncoder
import os
from dotenv import load_dotenv
from cogs import roles
import logging
logger = logging.getLogger('discord')
logger.setLevel(logging.WARNING)
handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)
load_dotenv()
token = os.getenv("TOKEN")
intents = discord.Intents.default()
intents.members = True
intents.guilds = True
bot = commands.Bot(command_prefix="g!", intents=intents)
last_msg = None
last_msg1 = None
@bot.event
async def on_ready():
print("My body is ready!")
activity = discord.Activity(name=f'anime', type=discord.ActivityType.watching)
await bot.change_presence(status = discord.Status.online, activity=activity)
@bot.event
async def on_resumed():
print("resume")
@bot.event
async def on_disconnect():
print("disconnected")
@bot.check
async def globally_block_dms(ctx):
return ctx.guild is not None
#Dealing With Cog Shit
#Load Cog
@bot.command(hidden=True)
@commands.is_owner()
async def load(ctx, extension):
bot.load_extension(f'cogs.{extension}')
await ctx.message.add_reaction('✅')
await ctx.message.delete(delay=2)
print(f'{extension} loaded')
#Unload Cog
@bot.command(hidden=True)
@commands.is_owner()
async def unload(ctx, extension):
bot.unload_extension(f'cogs.{extension}')
await ctx.message.add_reaction('✅')
await ctx.message.delete(delay=2)
print(f'{extension} unloaded')
#Reload Cog
@bot.command(hidden=True)
@commands.is_owner()
async def reload(ctx, extension):
# search cog by name instead
try:
bot.reload_extension(f'cogs.{extension}')
await ctx.message.add_reaction('✅')
await ctx.message.delete(delay=2)
print(f'{extension} reloaded')
except:
await ctx.message.add_reaction('❌')
await ctx.message.delete(delay=2)
print("extension not found")
return
#Preload Cogs
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
bot.load_extension(f'cogs.{filename[:-3]}')
print(f'{filename} loaded')
@bot.event
async def on_message(message):
channel = message.channel
if message.author == bot.user:
return
has_attchmt = message.attachments and len(message.attachments)
log_str = f"""
Guild: **{message.guild.name}** *({message.guild.id})*
Channel: **{channel.name}** *({channel.id})*
User: **{message.author}** *(Server name: **{message.author.display_name}**)* - ID: {message.author.id}
Message: {message.clean_content}
{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"""
if has_attchmt:
filenames = ", ".join([f"[{a.id}]{a.filename} - {a.proxy_url} ({round(a.size/1000, 2)}KB)" for a in message.attachments])
attchmt_str = f"Files attached ({len(message.attachments)}): {filenames}"
log_str += f"\n[{attchmt_str}]"
if not message.author.bot and channel.name != "mudae":
print(log_str)
if message.content == "Hi":
await channel.send("Nice to meet you")
# with open("bad_words.txt") as file:
# bad_words = [bad_word.strip().lower() for bad_word in file.readlines()]
# for bad_word in bad_words:
# if message.content.lower().count(bad_word) > 0:
# embed = discord.Embed(title ="You said a bad word", description="I will put you in the naughty corner")
# await channel.send(content= None, embed = embed)
# await message.delete()
await bot.process_commands(message)
@bot.event
async def on_command_error(ctx, error):
if ctx.command is None:
print("Unknown command")
return
command_args_arr = [i for i in ctx.command.clean_params.keys()]
command_args = f"`{'`, `'.join(command_args_arr)}`"
# Maybe only print certain type of arguments? https://docs.python.org/3/library/inspect.html#inspect.Parameter
# Or don't print them this way (use command.usage property/do per command error)
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send(f"Missing parameter {command_args} to use the command")
else:
# TODO: not hardcode the channel ID
debug_channel: discord.TextChannel = ctx.guild.get_channel(704780969453813822)
await debug_channel.send(content=error)
await ctx.message.add_reaction('❌')
print(error)
loop = asyncio.get_event_loop()
try:
print('starting')
loop.run_until_complete(bot.start(token))
except KeyboardInterrupt:
loop.run_until_complete(bot.logout())
# cancel all tasks lingering
except Exception as e:
print(e)
finally:
loop.close()