Skip to content
Merged
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
4 changes: 1 addition & 3 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,4 @@ requests==2.27.1
aiohttp==3.7.4
typing==3.7.4.3
async-timeout==3.0.1
psycopg2==2.9.3
config==0.5.1
configparser==5.2.0
asyncpg==0.25.0
90 changes: 49 additions & 41 deletions src/bot.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import discord
import os
import datetime
import psycopg2
import asyncpg
from datetime import datetime
from discord.ext import commands


Expand All @@ -12,90 +12,98 @@ class Bot(commands.Bot):
EXHAUSTED_FACE = 'https://user-images.githubusercontent.com/63065397/156922064-95c73c2a-b6cb-402e-b24b-d79fe7bf520a.png'
DEX_YELLOW = 0x8e38ce
REPOSITORY_URL = 'https://github.com/code-chaser/dex/'
DB_CONNECTION = None

def __init__(self, *args, **kwargs):
self.connect_to_db()
super().__init__(
command_prefix=self.get_prefix,
command_prefix=self.get_pref,
intents=discord.Intents.all(),
activity=discord.Activity(
type=discord.ActivityType.listening,
name="$dex help",
large_image_url=self.EXHAUSTED_FACE,
small_image_url=self.EXHAUSTED_FACE,
start=datetime.datetime(2022, 2, 24),
start=datetime(2022, 2, 24),
),
)
self.DB_CONNECTION = None
self.DATABASE = {}
self.loop.create_task(self.startup())

for file in os.listdir('./src/cogs'):
if file.endswith('.py'):
self.load_extension(f'src.cogs.{file[:-3]}')

def connect_to_db(self) -> None:
self.DB_CONNECTION = psycopg2.connect(
async def connect_to_db(self) -> None:
self.DB_CONNECTION = await asyncpg.connect(
host=os.getenv('DEX_DB_HOST'),
database=os.getenv('DEX_DB_NAME'),
user=os.getenv('DEX_DB_USER'),
port=os.getenv('DEX_DB_PORT'),
password=os.getenv('DEX_DB_PASSWORD'),
password=os.getenv('DEX_DB_PASSWORD')
)
print("\nDATABASE CONNECTED\n")

async def get_prefix(self, message):
cur = self.DB_CONNECTION.cursor()
cur.execute('SELECT prefix FROM guilds WHERE guild_id = \'' +
str(message.guild.id) + '\';')
prefix = cur.fetchone()
return prefix
async def clone_database(self):
await self.DB_CONNECTION.execute('CREATE TABLE IF NOT EXISTS guilds (guild_id VARCHAR(27) NOT NULL, prefix VARCHAR(108) NOT NULL, tag_messages SWITCH NOT NULL, PRIMARY KEY (guild_id));')
self.DATABASE['guilds'] = {}
self.DATABASE['guilds'] = {result['guild_id']: {k: v for k, v in result.items() if k != 'guild_id'} for result in await self.DB_CONNECTION.fetch("SELECT * FROM guilds")}
print("\nDATABASE CLONED\n")
print("\n\n****DATABASE DICTIONARY****\n\n")
print(self.DATABASE)
print("\n\n")
return

async def startup(self):
print("\nINSIDE Bot.startup()\n")
await self.connect_to_db()
await self.clone_database()

def get_pref(self, _, message):
return self.DATABASE['guilds'][str(message.guild.id)]['prefix']

def run(self) -> None:
super().run(os.getenv('DEX_BOT_TOKEN'))

async def on_ready(self):
print('Logged in as {0.user}'.format(self))
cur = self.DB_CONNECTION.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS guilds (guild_id VARCHAR(27) NOT NULL, prefix VARCHAR(108) NOT NULL, tag_messages SWITCH NOT NULL, PRIMARY KEY (guild_id));')
self.DB_CONNECTION.commit()

async def on_guild_join(self, guild) -> None:
cur = self.DB_CONNECTION.cursor()
cur.execute('INSERT INTO guilds (guild_id,prefix,tag_messages) VALUES (\'' +
str(guild.id)+'\', \'$dex \', \'on\');')
self.DB_CONNECTION.commit()
cur.close()

async def on_guild_join(self, guild):
if str(guild.id) in self.DATABASE['guilds'].keys():
return
await self.DB_CONNECTION.execute('INSERT INTO guilds (guild_id,prefix,tag_messages) VALUES (\'' +
str(guild.id)+'\', \'$dex \', \'on\');')
self.DATABASE['guilds'][str(guild.id)] = {}
self.DATABASE['guilds'][str(guild.id)] = {
'prefix': '$dex ', 'tag_messages': 'on'}
for channel in guild.text_channels:
if channel.permissions_for(guild.me).send_messages:
general = channel
if general is not None:
await general.send(embed=self.intro_msg_embed(guild))
return

async def on_guild_remove(self, guild) -> None:
cur = self.DB_CONNECTION.cursor()
cur.execute('DELETE FROM guilds WHERE guild_id = \'' +
str(guild.id) + '\';')
self.DB_CONNECTION.commit()
cur.close()
async def on_guild_remove(self, guild):
await self.DB_CONNECTION.execute('DELETE FROM guilds WHERE guild_id = \'' +
str(guild.id) + '\';')
if str(guild.id) in self.DATABASE['guilds'].keys():
self.DATABASE['guilds'].pop(str(guild.id))
return

async def on_message(self, message) -> None:
async def on_message(self, message):
await self.process_commands(message)
cur = self.DB_CONNECTION.cursor()
cur.execute('SELECT tag_messages FROM guilds WHERE guild_id = \'' +
str(message.guild.id) + '\';')
tag_switch = cur.fetchone()
cur.close()
tag_switch = self.DATABASE['guilds'][str(
message.guild.id)]['tag_messages']
target = message.author
if target == self.user:
return
print("\n\n-----------------------\n-----------------------\n\n" +
str(message.content) + "\n-----------------------\n")
if tag_switch[0] == 'off':
if tag_switch == 'off':
return
embed = discord.Embed(
title='Message Tagged',
colour=target.colour,
timestamp=datetime.datetime.utcnow(),
timestamp=datetime.utcnow(),
)
embed.set_footer(
text=''.join('`<prefix> tags off` -to turn this off'),
Expand All @@ -109,7 +117,7 @@ async def on_command_error(self, ctx, error) -> None:
embed = discord.Embed(
title='Status',
colour=0xff0000,
timestamp=datetime.datetime.utcnow(),
timestamp=datetime.utcnow(),
)
if isinstance(error, commands.MissingPermissions):
n = 'Error'
Expand Down Expand Up @@ -141,7 +149,7 @@ def intro_msg_embed(self, guild):
title='**GREETINGS!**',
description=description,
color=self.DEX_YELLOW,
timestamp=datetime.datetime.utcnow(),
timestamp=datetime.utcnow(),
)
embed.set_image(url=self.INTRO_IMG_URL)
embed.set_author(
Expand Down
18 changes: 9 additions & 9 deletions src/cogs/fun.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import discord
import aiohttp
import os
import datetime
import typing
from typing import Optional
from datetime import datetime
from discord.ext import commands


Expand All @@ -22,7 +22,7 @@ async def get_iquote(self):
async def inspire_command(self, ctx):
embed = discord.Embed(title="Inspirational Quote",
colour=ctx.author.colour,
timestamp=datetime.datetime.utcnow())
timestamp=datetime.utcnow())
iquote = await self.get_iquote()
embed.add_field(name="Quote", value=iquote[0]['q'], inline=False)
embed.add_field(name="Author", value=iquote[0]['a'], inline=False)
Expand All @@ -42,7 +42,7 @@ async def apod_command(self, ctx):
embed = discord.Embed(title="NASA",
description="Picture of the day",
colour=0x0B3D91,
timestamp=datetime.datetime.utcnow())
timestamp=datetime.utcnow())
embed.set_thumbnail(
url="https://user-images.githubusercontent.com/63065397/156291255-4af80382-836c-4801-8b4f-47da33ea36c5.png")
embed.set_footer(text="updated daily at 05:00:00 UTC [00:00:00 ET]")
Expand All @@ -65,7 +65,7 @@ async def get_meme(self):
async def meme_command(self, ctx):
embed = discord.Embed(title="MEME",
colour=0xffee00,
timestamp=datetime.datetime.utcnow())
timestamp=datetime.utcnow())
meme = await self.get_meme()
embed.add_field(name="Post Link", value=meme["postLink"], inline=True)
embed.add_field(name="Author", value=meme["author"], inline=True)
Expand All @@ -84,14 +84,14 @@ async def get_subreddit(self, subreddit):
return (data_json)

@commands.command(name="reddit", aliases=["subreddit"], help="shows top headlines of the given subreddit")
async def subreddit_command(self, ctx, subreddit, number: typing.Optional[int]):
async def subreddit_command(self, ctx, subreddit, number: Optional[int]):
data = await self.get_subreddit(subreddit)
if ('message' in data.keys()):
if data['message'] == "Not Found":
embed = discord.Embed(
title="Status",
colour=0xff0000,
timestamp=datetime.datetime.utcnow()
timestamp=datetime.utcnow()
)
embed.add_field(name="Error", value="Not Found", inline=True)
embed.set_footer(text="given subreddit: "+subreddit)
Expand All @@ -101,7 +101,7 @@ async def subreddit_command(self, ctx, subreddit, number: typing.Optional[int]):
title="Error",
description="API Request Fail",
colour=0xff0000,
timestamp=datetime.datetime.utcnow()
timestamp=datetime.utcnow()
)
for key_i in data.keys():
if key_i != 'message' and key_i != 'error':
Expand All @@ -117,7 +117,7 @@ async def subreddit_command(self, ctx, subreddit, number: typing.Optional[int]):
await ctx.send(embed=embed)
else:
embed = discord.Embed(title=str("/r/"+subreddit),
colour=0xff5700, timestamp=datetime.datetime.utcnow())
colour=0xff5700, timestamp=datetime.utcnow())
embed.set_thumbnail(
url="https://user-images.githubusercontent.com/63065397/156344382-821872f3-b6e3-46e7-b925-b5f1a0821da8.png")
i = 1
Expand Down
18 changes: 8 additions & 10 deletions src/cogs/info.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
import discord
from typing import Optional
from datetime import datetime
from discord import Embed, Member, Guild
from discord.ext.commands import Cog
from discord.ext.commands import command
from discord.ext import commands


class Info(Cog):
class Info(commands.Cog):
def __init__(self, bot):
self.bot = bot

@command(name="userinfo", aliases=["ui", "memberinfo", "mi"], help="shows user info")
async def userinfo_command(self, ctx, target: Optional[Member]):
@commands.command(name="userinfo", aliases=["ui", "memberinfo", "mi"], help="shows user info")
async def userinfo_command(self, ctx, target: Optional[discord.Member]):
target = target or ctx.author
embed = Embed(title="User Information",
embed = discord.Embed(title="User Information",
colour=target.colour,
timestamp=datetime.utcnow())
embed.set_thumbnail(url=target.avatar_url)
Expand All @@ -35,16 +33,16 @@ async def userinfo_command(self, ctx, target: Optional[Member]):
embed.add_field(name=n, value=v, inline=i)
await ctx.send(embed=embed)

@command(name="serverinfo", aliases=["si", "guildinfo", "gi"], help="shows server information")
async def serverinfo_command(self, ctx, target: Optional[Guild]):
@commands.command(name="serverinfo", aliases=["si", "guildinfo", "gi"], help="shows server information")
async def serverinfo_command(self, ctx, target: Optional[discord.Guild]):
flag = True
if(target):
flag = False
for g in self.bot.guilds:
if g.id == target.id:
flag = True
target = target or ctx.guild
embed = Embed(title="Server Information",
embed = discord.Embed(title="Server Information",
colour=ctx.guild.owner.colour,
timestamp=datetime.utcnow())
if flag == False:
Expand Down
Loading