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

Use d.py tasks & handle NotFound error #1

Merged
merged 3 commits into from Oct 11, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
55 changes: 27 additions & 28 deletions screamer/bot.py
@@ -1,12 +1,13 @@
from __future__ import unicode_literals

import asyncio
import logging
import sys
from datetime import datetime
from io import TextIOWrapper

import discord
from discord.errors import NotFound
from discord.ext import tasks

from screamer.config import Config

Expand All @@ -17,44 +18,42 @@
sys.stdout = TextIOWrapper(sys.stdout.detach(), encoding=sys.stdout.encoding, errors="replace", line_buffering=True)


# Timestamp string
def timestamp() -> str:
return datetime.utcnow().isoformat()


# Message content
def content() -> str:
return "\N{ZERO WIDTH SPACE} \N{ANTENNA WITH BARS} Alive at `" + timestamp() + "`"


# The bot
class Screamer(discord.Client):

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.config = kwargs["config"]
self.message = None
self.scream_message = None

async def started(self):
@staticmethod
def timestamp() -> str:
return datetime.utcnow().isoformat()

@staticmethod
def scream_content() -> str:
return "\N{ZERO WIDTH SPACE} \N{ANTENNA WITH BARS} Alive at `" + Screamer.timestamp() + "`"

async def scream_start(self):
channel = await self.fetch_channel(self.config.channel)
await channel.send("\N{WHITE HEAVY CHECK MARK} **Started at `" + timestamp() + "`**")
self.message = await channel.send(content())

async def screamer(self):
while True:
try:
if self.message is None:
await self.started()
else:
await self.message.edit(content=content())
except Exception as e:
print(e)
await asyncio.sleep(15)
await channel.send("\N{WHITE HEAVY CHECK MARK} **Started at `" + Screamer.timestamp() + "`**")
self.scream_message = await channel.send(Screamer.scream_content())

@tasks.loop(seconds=15)
async def scream_task(self):
try:
if self.scream_message is None:
await self.scream_start()
else:
await self.scream_message.edit(content=Screamer.scream_content())
except NotFound:
await self.scream_start()
except Exception as e:
print(e)

async def on_ready(self):
print("Connected as " + self.user.name + " (" + str(self.user.id) + ")")

self.loop.create_task(self.screamer())
self.scream_task.start()

def run(self):
super().run(self.config.token)
Expand Down