Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/rdb integration #55

Merged
merged 60 commits into from
Sep 15, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
60 commits
Select commit Hold shift + click to select a range
8f148ac
Adding support section to readme
Aug 12, 2021
d95e106
Making readme more generic
Aug 14, 2021
ee2c10a
Merge branch 'main' of github.com:DMcP89/harambot into dev
Aug 18, 2021
e48afed
removing server.py
Aug 18, 2021
62c4a9c
Merge pull request #30 from DMcP89/dev
DMcP89 Sep 9, 2021
d1763a7
Add example images to readme
Sep 14, 2021
e309ccf
Updating Readme
Sep 14, 2021
0cbe2e0
Merge pull request #33 from DMcP89/dev
DMcP89 Sep 14, 2021
e7b0f20
Merge pull request #26 from DMcP89/dependabot/pip/pyyaml-5.4
DMcP89 Sep 17, 2021
d1cf429
Merge pull request #23 from DMcP89/dependabot/pip/py-1.10.0
DMcP89 Sep 17, 2021
dfc9765
updating discord.py version
Sep 17, 2021
d4a4c90
Merge pull request #36 from DMcP89/dev
DMcP89 Sep 17, 2021
6579380
Merge pull request #37 from DMcP89/main
DMcP89 Sep 17, 2021
ccefe81
Merge pull request #27 from DMcP89/dependabot/pip/aiohttp-3.7.4
DMcP89 Sep 17, 2021
a0c810f
Merge pull request #38 from DMcP89/main
DMcP89 Sep 17, 2021
bcd79ea
Merge pull request #39 from DMcP89/main
DMcP89 Sep 17, 2021
0cf8960
Merge pull request #24 from DMcP89/dependabot/pip/websockets-9.1
DMcP89 Sep 17, 2021
21f3973
Merge branch 'dependabot/pip/urllib3-1.26.5' into main
DMcP89 Sep 17, 2021
93aff48
Bumping urllib3
Sep 17, 2021
ee3b799
Merge branch 'main' of github.com:DMcP89/harambot into dev
Sep 17, 2021
7e42672
fixing typo
Sep 17, 2021
7a564a6
Merge pull request #41 from DMcP89/dev
DMcP89 Sep 17, 2021
6bdeaaa
Merge pull request #41 from DMcP89/dev
DMcP89 Sep 17, 2021
9883535
Quick fix for issue #22
Dec 1, 2021
9d83a99
Merge pull request #44 from DMcP89/dev
DMcP89 Dec 1, 2021
c3d50ea
Merge pull request #44 from DMcP89/dev
DMcP89 Dec 1, 2021
e2c743d
Updating trade command to handle no trades
Dec 2, 2021
61ce27c
Merge pull request #46 from DMcP89/dev
DMcP89 Dec 2, 2021
d588e4b
Merge pull request #46 from DMcP89/dev
DMcP89 Dec 2, 2021
092b5ed
Create FUNDING.yml
DMcP89 Dec 5, 2021
8c4fb71
Create FUNDING.yml
DMcP89 Dec 5, 2021
fc1c5cb
Adding heroky.yml
Dec 9, 2021
265443c
Created POC for handling Yahoo auth via callbacks
Dec 9, 2021
526d474
Updated join event to prompt owner to configure
Dec 21, 2021
0b89177
removing server.py poc
Dec 21, 2021
408523c
Merge pull request #47 from DMcP89/feature/bot_based_configuration
DMcP89 Dec 21, 2021
1a8433b
Adding Procfile
Dec 22, 2021
169933a
Updating datastore to create guilds file if it does not exist
Dec 22, 2021
ccc9aec
Changing envvar prefix for dynaconf
Dec 22, 2021
d476df8
Changing Procfile to use make, removing heroku.yml
Dec 22, 2021
77fac2a
adding app.json file
Dec 22, 2021
358a14d
adding blank guilds.json to tracking
Dec 22, 2021
613b7cf
adding guilds.json to gitignore
Dec 22, 2021
248e9a5
Merge branch 'main' of https://git.heroku.com/hml-harambot into enhan…
Dec 22, 2021
cb59c87
removing guilds file from tracking
Dec 22, 2021
ed95233
Merge branch 'dev' into enhancement/heroku-deployments
DMcP89 Aug 2, 2022
4d8642b
installed peewee orm
DMcP89 Aug 2, 2022
50a99f8
renamed harambot.py to bot.py
DMcP89 Sep 14, 2022
9d5896d
Removed trailing lines from config.py
DMcP89 Sep 14, 2022
f6a69c3
Created model.py to begin migration to RDBs for guild management
DMcP89 Sep 14, 2022
037f3c0
Added *.db to gitignore
DMcP89 Sep 14, 2022
826686b
Change player_details command to stats
DMcP89 Sep 14, 2022
a5de071
Migrated guild management to peewee from local json file
DMcP89 Sep 14, 2022
aa56333
Removing old datastore tests
DMcP89 Sep 14, 2022
aef09cf
Adding configurations for mysql and postgres dbs
DMcP89 Sep 15, 2022
38f6e02
Creating enum for supported database types
DMcP89 Sep 15, 2022
66eaa77
Adding comment to settings.toml listing supported values
DMcP89 Sep 15, 2022
88120ef
Updating if statement to use enum values
DMcP89 Sep 15, 2022
1ea0f61
Refactored directory structure for database modules
DMcP89 Sep 15, 2022
874124f
Merge branch 'main' of github.com:DMcP89/harambot into feature/rdb_in…
DMcP89 Sep 15, 2022
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
12 changes: 12 additions & 0 deletions .github/FUNDING.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# These are supported funding model platforms

github: [DMcP89]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ guilds.json
answers.txt
*.pem
.python-version
*.db
1 change: 1 addition & 0 deletions Procfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
worker: make run
33 changes: 33 additions & 0 deletions app.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"name": "Harambot",
"description": "A Yahoo Fantasy sports bot for Discord.",
"keywords": [
"fantasy football",
"discord",
"yahoo",
"chat bot",
"ff",
"harambe"
],
"website" : "https://github.com/DMcP89/harambot",
"repository": "https://github.com/DMcP89/harambot",
"env": {
"HARAMBOT_YAHOO_KEY" : {
"description": "Yahoo Consumer Key",
"value": "",
"required": "true"
},
"HARAMBOT_YAHOO_SECRET" : {
"description": "Yahoo Consumer Secret",
"value": "",
"required": "true"
},
"HARAMBOT_DISCORD_TOKEN" : {
"description": "Discord bot token",
"value": "",
"required": "true"
}
}


}
4 changes: 3 additions & 1 deletion config/settings.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
[default]
LOGLEVEL = "DEBUG"
GUILDS_DATASTORE_LOC = "config/guilds.json"
# Supported databases are sqlite, mysql, and postgres
GUILDS_DATASTORE_TYPE = "sqlite"
GUILDS_DATASTORE_LOC = "harambot.db"
81 changes: 81 additions & 0 deletions harambot/bot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import os

import logging
import discord
import requests
import base64
import time
from yahoo_fantasy_api import game
from yahoo_oauth import OAuth2


from discord.ext import commands
from cogs.meta import Meta
from cogs.misc import Misc
from cogs.yahoo import Yahoo
from config import settings
from database.models import Guild

#logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('harambot.py')
logger.setLevel(settings.loglevel)

intents = discord.Intents.default()
intents.members = True

bot = commands.Bot(command_prefix="$", description="", intents=intents)
bot.remove_command('help')



@bot.event
async def on_ready():
logger.info("Everything's all ready to go~")

@bot.event
async def on_guild_join(guild):
logger.info("Joined {}".format(guild.name))
if not Guild.select().where(Guild.guild_id == str(guild.id)).exists():
await configure_guild(guild.owner, guild.id)
logger.info("Guild not configured!")


async def configure_guild(owner, id):

def check(m):
return m.author == owner

await owner.send("Thank you for adding Harambot to your server!")
await owner.send("Please open the following link to authorize with Yahoo, respond with the code given after authorization")
await owner.send("https://api.login.yahoo.com/oauth2/request_auth?redirect_uri=oob&response_type=code&client_id={}".format(settings.yahoo_key))
code = await bot.wait_for('message', timeout=60, check=check)
encoded_creds = base64.b64encode(('{0}:{1}'.format(settings.yahoo_key, settings.yahoo_secret )).encode('utf-8'))
details = requests.post(
url='https://api.login.yahoo.com/oauth2/get_token',
data={"code": code.clean_content, 'redirect_uri': 'oob', 'grant_type': 'authorization_code'},
headers = {
'Authorization': 'Basic {0}'.format(encoded_creds.decode('utf-8')),
'Content-Type': 'application/x-www-form-urlencoded'
}
).json()
details['token_time'] = time.time()
await owner.send("Enter Yahoo League ID")
leauge_id = await bot.wait_for('message', timeout=60, check=check)
await owner.send("Enter Yahoo League Type(nfl, nhl, nba, mlb)")
leauge_type = await bot.wait_for('message', timeout=60, check=check)
await owner.send("Enter text to use with $RIP command")
RIP_text = await bot.wait_for('message', timeout=60, check=check)
await owner.send("Enter image url to use with $RIP command")
RIP_image_url = await bot.wait_for('message', timeout=60, check=check)
details["league_id"] = leauge_id.clean_content
details["league_type"] = leauge_type.clean_content
details["RIP_text"] = RIP_text.clean_content
details["RIP_image_url"] = RIP_image_url.clean_content
Guild.create(guild_id=id,**details)
return

bot.add_cog(Meta(bot))
bot.add_cog(Yahoo(bot, settings.yahoo_key, settings.yahoo_secret))
bot.add_cog(Misc(bot))

bot.run(settings.discord_token, bot=True, reconnect=True) # Where 'TOKEN' is your bot token
2 changes: 1 addition & 1 deletion harambot/cogs/meta.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ async def help(self, ctx):
embed.add_field(name="$RIP", value="Pay respects to Harambe", inline=False)
embed.add_field(name="$standings", value="Returns the current standings of your league", inline=False)
embed.add_field(name="$roster team_name", value="Returns the roster of the given team", inline=False)
embed.add_field(name="$player_details player_name", value="Returns the details of the given player", inline=False)
embed.add_field(name="$stats player_name", value="Returns the details of the given player", inline=False)
embed.add_field(name="$trade", value="Create poll for latest trade for league approval", inline=False)
embed.add_field(name="$matchups", value="Returns the current weeks matchups", inline=False)
await ctx.send(embed=embed)
Expand Down
11 changes: 6 additions & 5 deletions harambot/cogs/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,23 @@
import discord
import logging

from database.models import Guild

logger = logging.getLogger(__file__)
logger.setLevel(logging.INFO)

class Misc(commands.Cog):

def __init__(self, bot, guilds):
def __init__(self, bot):
self.bot = bot
self.guilds = guilds

@commands.command("RIP")
async def RIP(self, ctx, *args):
logger.info("RIP called")
league_details = self.guilds.getGuildDetails(ctx.guild.id)
guild = Guild.get(Guild.guild_id == str(ctx.guild.id))
respected = args[0] if args else "Harambe"
message = league_details["RIP_text"] +" "+ respected
message = guild.RIP_text +" "+ respected
embed = discord.Embed(title="", description='', color=0xeee657)
embed.set_image(url=league_details["RIP_image_url"])
embed.set_image(url=guild.RIP_image_url)

await ctx.send(content=message,embed=embed)
13 changes: 7 additions & 6 deletions harambot/cogs/yahoo.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
from discord import embeds
from discord.ext import commands
from yahoo_oauth import OAuth2
from playhouse.shortcuts import model_to_dict


import discord
import logging
import urllib3
import yahoo_api

from database.models import Guild


logger = logging.getLogger(__file__)
Expand All @@ -18,8 +20,8 @@

def oauth(func):
async def setup(cog, ctx, *, content=None):
league_details = cog.guilds.getGuildDetails(ctx.guild.id)
cog.yahoo_api = yahoo_api.Yahoo(OAuth2(cog.KEY, cog.SECRET, **league_details), league_details["league_id"], league_details["league_type"])
guild = Guild.get(Guild.guild_id == str(ctx.guild.id))
cog.yahoo_api = yahoo_api.Yahoo(OAuth2(cog.KEY, cog.SECRET, **model_to_dict(guild)), guild.league_id, guild.league_type)
if content:
await func(cog, ctx, content=content)
else:
Expand All @@ -31,12 +33,11 @@ class Yahoo(commands.Cog):

error_message = "I'm having trouble getting that right now please try again later"

def __init__(self, bot, KEY, SECRET, guilds):
def __init__(self, bot, KEY, SECRET):
self.bot = bot
self.http = urllib3.PoolManager()
self.KEY = KEY
self.SECRET = SECRET
self.guilds = guilds
self.yahoo_api = None


Expand Down Expand Up @@ -112,9 +113,9 @@ async def trade(self, ctx):
await msg.add_reaction(no_emoji)


@commands.command("player_details")
@commands.command("stats")
@oauth
async def player_details(self, ctx, *, content:str):
async def stats(self, ctx, *, content:str):
logger.info("player_details called")
details = self.yahoo_api.get_player_details(content)
if details:
Expand Down
6 changes: 2 additions & 4 deletions harambot/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@
from dynaconf import Dynaconf

settings = Dynaconf(
envvar_prefix="DYNACONF",
envvar_prefix="HARAMBOT",
settings_files=['settings.toml', '.secrets.toml'],
environments=True,
)


)
6 changes: 6 additions & 0 deletions harambot/database/databasetype.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from enum import Enum

class DatabaseType(Enum):
SQLITE = 'sqlite'
MYSQL = 'mysql'
POSTGRES = 'postgres'
34 changes: 34 additions & 0 deletions harambot/database/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from peewee import *
from config import settings
from database.databasetype import DatabaseType

if settings.guilds_datastore_type == DatabaseType.POSTGRES:
database = PostgresqlDatabase(settings.guild_db,user=settings.guild_db_user, password=settings.guild_db_pass,
host=settings.guild_db_host, port=settings.guild_db_port)
elif settings.guilds_datastore_type == DatabaseType.MYSQL:
database = MySQLDatabase(settings.guild_db,user=settings.guild_db_user, password=settings.guild_db_pass,
host=settings.guild_db_host, port=settings.guild_db_port)
elif settings.guilds_datastore_type == DatabaseType.SQLITE:
database = SqliteDatabase(settings.guilds_datastore_loc)
else:
database = SqliteDatabase(':memory:')


class BaseModel(Model):
class Meta:
database = database


class Guild(BaseModel):
guild_id = TextField(unique=True)
access_token = TextField()
refresh_token = TextField()
expires_in = IntegerField()
token_type = TextField()
xoauth_yahoo_guid = TextField()
token_time = BigIntegerField()
league_id = TextField()
league_type = TextField()
RIP_text = TextField()
RIP_image_url = TextField()

24 changes: 0 additions & 24 deletions harambot/datastore.py

This file was deleted.

38 changes: 0 additions & 38 deletions harambot/harambot.py

This file was deleted.

1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,4 @@ yahoo-fantasy-api==2.4.0
yahoo-oauth==1.1
yarl==1.3.0
zipp==3.4.0
peewee==3.15.1
10 changes: 0 additions & 10 deletions tests/test-guilds.json

This file was deleted.

Loading