Skip to content

Commit

Permalink
Merge pull request #9 from AngelOnFira/add-logging
Browse files Browse the repository at this point in the history
Add logging for production environment
  • Loading branch information
AlanReviews authored Jan 5, 2025
2 parents 3264c13 + f795bf1 commit 75d396b
Show file tree
Hide file tree
Showing 7 changed files with 40 additions and 4 deletions.
1 change: 1 addition & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ENVIRONMENT=development
2 changes: 2 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,6 @@ WORKDIR /app

RUN pip install -r requirements.txt

ENV ENVIRONMENT=production

CMD ["python", "main.py"]
16 changes: 15 additions & 1 deletion cogs/Basics.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from discord import File, Embed, channel
from discord.ext import commands
import random
import logging

class Basics(commands.Cog):
def __init__(self, bot):
Expand All @@ -11,29 +12,34 @@ def __init__(self, bot):
@commands.command()
async def ping(self, ctx, name: str = None):
"""Check my websocket latency"""
logging.info(f"Ping command invoked by {ctx.author}")
await ctx.send(f'My ping is {round(self.bot.latency * 100,2)} ms!')

@commands.command()
async def hug(self, ctx, name: str = None):
"""I give users a hug"""
name = name or ctx.author.name
logging.info(f"Hug command invoked by {ctx.author} for {name}")
await ctx.send(f"I give a hug to {name}!")

@commands.command(name='eightball', aliases=['8ball'])
async def eightball(self, ctx, arg):
"""I predict the future"""
output = ["Yes", "No", "Unsure", "Can't answer right now"]
logging.info(f"Eightball command invoked by {ctx.author} with argument {arg}")
await ctx.send(output[random.randint(0, len(output))])

@commands.command()
async def echo(self, ctx, *args):
"""I repeat what you say"""
logging.info(f"Echo command invoked by {ctx.author} with arguments {' '.join(args)}")
await ctx.send(' '.join(ctx.message.content.split()[1:]))
await ctx.message.delete()

@commands.command()
async def quote(self, ctx):
"""I give a quote from Zen Quotes"""
logging.info(f"Quote command invoked by {ctx.author}")
async with aiohttp.ClientSession() as cs:
async with cs.get("https://zenquotes.io/api/random") as r:
res = await r.json() # returns dict
Expand All @@ -43,6 +49,7 @@ async def quote(self, ctx):
@commands.command()
async def stats(self, ctx):
"""Check out my stats"""
logging.info(f"Stats command invoked by {ctx.author}")
total_memory, used_memory, free_memory = map(
int, os.popen('free -t -m').readlines()[-1].split()[1:])
memory_usage = round((used_memory/total_memory) * 100, 2)
Expand All @@ -55,11 +62,13 @@ async def stats(self, ctx):
@commands.command()
async def ubuntu(self, ctx):
"""Shows Ubuntu logo in ASCII format"""
logging.info(f"Ubuntu command invoked by {ctx.author}")
await ctx.send(file=File(fp="cogs/Ubuntu.png"))

@commands.command(name='roll', aliases=['dice'])
async def roll(self, ctx, dice: str):
"""Rolls a dice in NdN format."""
logging.info(f"Roll command invoked by {ctx.author} with dice {dice}")
try:
rolls, limit = map(int, dice.split('d'))
except Exception:
Expand All @@ -72,11 +81,13 @@ async def roll(self, ctx, dice: str):
@commands.command(name='choose', description='For when you wanna settle the score some other way')
async def choose(self, ctx, *choices: str):
"""Chooses between multiple choices."""
logging.info(f"Choose command invoked by {ctx.author} with choices {choices}")
await ctx.send(random.choice(choices))

@commands.command(name='dm')
async def dm(self, ctx):
"""Sends a hello in dms"""
logging.info(f"DM command invoked by {ctx.author}")
try:
await ctx.message.author.send("Hello there")
except:
Expand All @@ -85,11 +96,13 @@ async def dm(self, ctx):
@commands.command(name='faq', aliases=["questions"])
async def faq(self, ctx):
"""Sends you a link to the Alan Reviews FAQ page"""
logging.info(f"FAQ command invoked by {ctx.author}")
await ctx.send("What does Alan review? How do I request a video review? All the answers are in this link: https://alanreviews.github.io/alan-reviews-updates/faq/ You're welcome.")

@commands.command(name='links', aliases=['link'])
async def links(self, ctx):
"""Lists all my important links in an embed."""
logging.info(f"Links command invoked by {ctx.author}")
links = discord.Embed(title="List of Links",description="Here is a list of links. More will be added later. Enjoy!",colour=0xFF0000)
links.set_author(name="Alan")
links.add_field(name="YouTube", value="https://www.youtube.com/c/TheAlanReviews", inline=False)
Expand All @@ -102,11 +115,12 @@ async def links(self, ctx):
@commands.command(name='topic')
async def topic(self, ctx):
"""Provides a question for users to talk about"""
logging.info(f"Topic command invoked by {ctx.author}")
topics = ["What is your favourite book?", "What is your favourite game?",
"What is your favourite song with a positive message?", "What is your favourite place to visit?",
"Did you apply what you learned in school?", "What is your favourite programming language?", "What is your favourite website?"]
number = random.randint(0, len(topics))
await ctx.send(topics[number])

async def setup(bot):
await bot.add_cog(Basics(bot))
await bot.add_cog(Basics(bot))
4 changes: 4 additions & 0 deletions cogs/greetings.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import discord, os
from discord.ext import commands
import logging

class Greetings(commands.Cog):
def __init__(self, bot):
Expand All @@ -10,15 +11,18 @@ def __init__(self, bot):
async def on_member_join(self, member):
channel = member.guild.system_channel
if channel is not None:
logging.info(f"Member {member} joined the server")
await channel.send('Welcome {0.mention}.'.format(member))

@commands.command(name='hello', aliases=['hi', 'hey'])
async def hello(self, ctx, *, member: discord.Member = None):
"""Says hello"""
member = member or ctx.author
if self._last_member is None or self._last_member.id != member.id:
logging.info(f"Hello command invoked by {ctx.author} for {member}")
await ctx.send('Hello {0.name}'.format(member))
else:
logging.info(f"Hello command invoked by {ctx.author} for {member} (familiar)")
await ctx.send('Hello {0.name}... This feels familiar.'.format(member))
self._last_member = member

Expand Down
9 changes: 8 additions & 1 deletion cogs/moderation.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,16 @@
from discord import Embed, member
from discord.ext.commands import has_permissions, MissingPermissions
from typing import Optional
import logging

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

@commands.command()
async def serverinfo(self, ctx):
"""Shows server information in an embed"""
logging.info(f"Serverinfo command invoked by {ctx.author}")
embed = Embed(title="Server information")
embed.set_thumbnail(url = ctx.guild.icon)
fields = [("Name", ctx.guild.name, True), ("ID", ctx.guild.id, True), ("Creation date", ctx.guild.created_at.strftime("%d/%m/%Y %H:%M:%S"), True),("Member count", ctx.guild.member_count, True),
Expand All @@ -24,6 +27,7 @@ async def userinfo(self, ctx, user: discord.User = None):
"""Shows user information and their avatar in an embed"""
if user is None:
user = ctx.author
logging.info(f"Userinfo command invoked by {ctx.author} for {user}")
embed = Embed(title="User information", colour=user.colour)
embed.set_thumbnail(url=user.display_avatar)
fields = [("Name", str(user), False), ("ID", user.id, False), ("System", user.system, False), ("Bot", user.bot, False)]
Expand All @@ -36,6 +40,7 @@ async def userinfo(self, ctx, user: discord.User = None):
@commands.has_permissions(kick_members=True)
async def kick(self, ctx, member: discord.Member, reason = "not specified"):
"""Removes a member from the server. The member can rejoin that server. Only members with the kick members permission can use this command."""
logging.info(f"Kick command invoked by {ctx.author} for {member} with reason {reason}")
await member.send("You got kicked for " + reason)
await member.kick(reason=reason)
await ctx.send(f'User {member} has been kicked!')
Expand All @@ -44,12 +49,14 @@ async def kick(self, ctx, member: discord.Member, reason = "not specified"):
@commands.has_permissions(ban_members=True)
async def ban(self, ctx, member: discord.Member, reason = "not specified"):
"""Removes a member from a server. The member cannot rejoin the server until the member gets unbanned. Only members with the ban members permission can use this command."""
logging.info(f"Ban command invoked by {ctx.author} for {member} with reason {reason}")
try:
await member.send("You got banned for " + reason)
await member.ban(delete_message_days=7, reason=reason)
except Exception as e:
logging.error(f"Error banning user {member}: {e}")
return await ctx.send(e)
await ctx.send(f'User {member} got banned!')

async def setup(bot):
await bot.add_cog(moderation(bot))
await bot.add_cog(moderation(bot))
11 changes: 9 additions & 2 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,14 @@
PREFIX = os.getenv("PREFIX", default="!!")
activity = discord.Game(name="Bonjour!")

handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
ENVIRONMENT = os.getenv("ENVIRONMENT", default="development")

if ENVIRONMENT == "production":
handler = logging.StreamHandler()
else:
handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')

logging.basicConfig(level=logging.DEBUG, handlers=[handler])

# subclassing commands.Bot
class MyBot(commands.Bot):
Expand All @@ -34,4 +41,4 @@ async def setup_hook(self):
async def on_message(message):
await bot.process_commands(message)

bot.run(TOKEN, log_handler=handler, log_level=logging.DEBUG)
bot.run(TOKEN)
1 change: 1 addition & 0 deletions nomad.hcl
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ job "tara-bot" {
template {
data = <<EOH
DISCORD_TOKEN={{ with nomadVar "nomad/jobs/tara-bot" }}{{ .DISCORD_TOKEN }}{{ end }}
ENVIRONMENT=production
EOH

destination = "secrets/file.env"
Expand Down

0 comments on commit 75d396b

Please sign in to comment.