Skip to content

Commit

Permalink
Added background tasks: updates languages and server_count if true RTFM
Browse files Browse the repository at this point in the history
  • Loading branch information
Unactived committed Apr 6, 2019
1 parent a8b5bbc commit 29a70c9
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 38 deletions.
119 changes: 82 additions & 37 deletions bot.py
@@ -1,3 +1,4 @@
import asyncio
import sys

import aiohttp
Expand All @@ -22,45 +23,14 @@ def _prefix_callable(bot, message):

description = "A discord bot to help you in your daily programming discord life"


async def update_dbl_count(bot):
"""POST updated stats about the bot"""

guildCount = len(bot.guilds)
usersCount = sum([guild.member_count for guild in bot.guilds])
payload = {"server_count" : guildCount}

url = f"https://discordbots.org/api/bots/{bot.user.id}/stats"
headers = {"Authorization" : bot.config['DB_TOKEN']}

async with aiohttp.ClientSession() as aioclient:
await aioclient.post(url, data=payload, headers=headers)

url = f"https://botsfordiscord.com/api/bot/{bot.user.id}"
headers = {"Authorization" : bot.config['BFD_TOKEN']}

async with aiohttp.ClientSession() as aioclient:
await aioclient.post(url, data=payload, headers=headers)

url = f"https://discord.bots.gg/api/v1/bots/{bot.user.id}/stats"
headers = {"Authorization" : bot.config['DBGG_TOKEN'], "Content-Type": "application/json"}
payload = {"guildCount" : guildCount}

async with aiohttp.ClientSession() as aioclient:
await aioclient.post(url, data=json.dumps(payload), headers=headers)

url = f'https://discordbotlist.com/api/bots/{bot.user.id}/stats'
headers = {"Authorization" : f"Bot {bot.config['DBL_TOKEN']}", "Content-Type": "application/json"}
payload = {"guilds" : guildCount, "users": usersCount}

async with aiohttp.ClientSession() as aioclient:
await aioclient.post(url, data=json.dumps(payload), headers=headers)

async def log_guilds(bot, guild, joined: bool):
"""
Logs guilds adding/kicking the bot in the support server
"""
if bot.user.id != bot.config['ID']:
# true RTFM
return
logsChannel = bot.get_channel(bot.config['SUPPORT_LOG_CHANNEL_ID'])
if joined:
content = 'added RTFM to their community ! :smiley:'
Expand Down Expand Up @@ -90,13 +60,14 @@ def __init__(self, config):
self.load_extension(extension)
except Exception as e:
print(f"Couldn't load the following extension : {extension} ; :{e}", file=sys.stderr)
self.bg_task = self.loop.create_task(self.background_task())
self.bg_dbl_count = self.loop.create_task(self.background_dbl_count())

async def on_ready(self):
print(f'Logged in as {self.user.name} ; ID : {self.user.id}')
print('-------------------------------------------\n')
await self.change_presence(status=self.config['STATUS_TYPE'],
activity=discord.Game(name=self.config['STATUS']))
# await update_dbl_count(self)

async def on_resumed(self):
print(f'\n[*] {self.user} resumed...')
Expand All @@ -108,15 +79,89 @@ async def on_message(self, message):
await self.process_commands(message)

async def on_guild_join(self, guild):
await update_dbl_count(self)
await log_guilds(self, guild, True)

async def on_guild_remove(self, guild):
await update_dbl_count(self)
await log_guilds(self, guild, False)

async def close(self):
self.bg_dbl_count.cancel()
self.bg_task.cancel()
await super().close()

async def background_task(self):
await self.wait_until_ready()

url = 'https://tio.run/languages.json'

while not self.is_closed():
try:
async with aiohttp.ClientSession() as client_session:
async with client_session.get(url) as response:
if response.status != 200:
print(f"Couldn't reach languages.json (status code: {response.status}).")
continue

languages = sorted(json.loads(await response.text()))
textual = '\n'.join(languages)
with open('RTFMbot-master/languages.txt', 'r') as file:
current = file.read()

if textual != current:
with open('RTFMbot-master/languages.txt', 'w') as file:
file.write(textual)

self.languages = languages

await asyncio.sleep(300) # 5 minutes
except asyncio.CancelledError:
return

async def background_dbl_count(self):
"""POST updated stats about the self"""

await self.wait_until_ready()

if self.user.id != self.config['ID']:
# Only updates if it's the true RTFM
return

while not self.is_closed():
try:
guildCount = len(self.guilds)
usersCount = sum([guild.member_count for guild in self.guilds])
payload = {"server_count" : guildCount}

url = f"https://discordbots.org/api/bots/{self.user.id}/stats"
headers = {"Authorization" : self.config['DB_TOKEN']}

async with aiohttp.ClientSession() as aioclient:
await aioclient.post(url, data=payload, headers=headers)

url = f"https://botsfordiscord.com/api/bot/{self.user.id}"
headers = {"Authorization" : self.config['BFD_TOKEN']}

async with aiohttp.ClientSession() as aioclient:
await aioclient.post(url, data=payload, headers=headers)

url = f"https://discord.bots.gg/api/v1/bots/{self.user.id}/stats"
headers = {"Authorization" : self.config['DBGG_TOKEN'], "Content-Type": "application/json"}
payload = {"guildCount" : guildCount}

async with aiohttp.ClientSession() as aioclient:
await aioclient.post(url, data=json.dumps(payload), headers=headers)

url = f'https://discordbotlist.com/api/bots/{self.user.id}/stats'
headers = {"Authorization" : f"Bot {self.config['DBL_TOKEN']}", "Content-Type": "application/json"}
payload = {"guilds" : guildCount, "users": usersCount}

async with aiohttp.ClientSession() as aioclient:
await aioclient.post(url, data=json.dumps(payload), headers=headers)

await asyncio.sleep(300) # 5 minutes
except asyncio.CancelledError:
return

def run(self, token):
super().run(token, reconnect=True)

3 changes: 2 additions & 1 deletion config_example.yml
@@ -1,4 +1,5 @@
PREFIX: 'do '
ID: 495914599531675648
SUPPORT_LOG_CHANNEL_ID: 000000000000000000

# Discord access token
Expand Down Expand Up @@ -30,4 +31,4 @@ BLUE_RTFM: 0x1EDBF8
# What should the status read
STATUS: ''
# Integer designating the type of activity
STATUS_TYPE: '3'
STATUS_TYPE: '3'

0 comments on commit 29a70c9

Please sign in to comment.