Discord-Bot-Python/cogs/general.py

458 lines
14 KiB
Python

import platform
import os
import platform
import sys
import psutil
import math
import copy
import random
from random import randint
import datetime
import time
from time import time
from datetime import datetime
from datetime import datetime as dt
#from discord.utils import get
from discord.utils import *
import aiohttp
import discord
from discord import app_commands
from discord import Embed, Color
from discord.ext import commands
from discord.ext.commands import Context
from http.client import responses
from paginator import Paginator
from typing import Optional
from constants import (
LANGUAGES,
NEWLINES_LIMIT,
CHARACTERS_LIMIT,
Emoji,
JUDGE0_ICON,
START_TIME,
PREFIX,
)
from helpers import checks
class General(commands.Cog, name="general"):
def __init__(self, bot):
self.bot = bot
#-------------------------------------------------------------------------------
@commands.hybrid_command(
name="help",
description="List all commands the bot has loaded."
)
@checks.not_blacklisted()
async def help(self, context: Context) -> None:
prefix = self.bot.config["prefix"]
embed = discord.Embed(
title="Help", description="List of available commands:", color=0x9C84EF)
for i in self.bot.cogs:
cog = self.bot.get_cog(i.lower())
commands = cog.get_commands()
data = []
for command in commands:
description = command.description.partition('\n')[0]
data.append(f"{prefix}{command.name} - {description}")
help_text = "\n".join(data)
embed.add_field(name=i.capitalize(),
value=f'```{help_text}```', inline=False)
await context.send(embed=embed)
#-------------------------------------------------------------------------------
@commands.hybrid_command(
name="sinfo",
description="List bot server status info."
)
@checks.not_blacklisted()
async def sinfo(self, ctx):
#Sends useful information about the bot and links.
uptime = int((dt.utcnow() - START_TIME).total_seconds())
d, h = divmod(uptime, 86400)
h, m = divmod(h, 3600)
m, s = divmod(m, 60)
mem = psutil.virtual_memory()
pid = os.getpid()
memory_use = psutil.Process(pid).memory_info()[0]
data = [
("Process memory", f"{memory_use / math.pow(1024, 2):.2f}MB"),
("CPU Usage", f"{psutil.cpu_percent()}%"),
("RAM Usage", f"{mem.percent}%"),
]
embed = Embed(
title="BOT System",
url="https://discord.gg/ScektXnyBe",
timestamp=dt.utcnow(),
description="Discord bot for single custom servers",
)
embed.set_author(name=f"{ctx.author} request", icon_url=ctx.author.avatar)
embed.add_field(
name=f"YADMB#9063 - {self.bot.config['application_id']}",
value=(
f"Uptime: {d}d {h}h {m}m {s}s\n"
f"Servers connected: {len(self.bot.guilds)}\n"
f"Unique users: {len(self.bot.users)}"
f"Running on: {platform.system()} {platform.release()} ({os.name})"
),
inline=False
)
embed.add_field(
name=":computer: System status:",
value="\n".join(f"**{x[0]}** {x[1]}" for x in data),
inline=False
)
embed.add_field(
name="Links",
value=(
f":link: Invite me by clicking [here](https://discordapp.com/oauth2/authorize?&client_id={self.bot.config['application_id']}&scope=bot+applications.commands&permissions={self.bot.config['permissions']}).\n"
f":mortar_board: [GitHub](https://github.com/Die-Antwoord)\n"
f":information_source: [Support server](https://discord.gg/ScektXnyBe)\n"
#f"<:paypal:707665144276320277> [Donation on PayPal](https://paypal.me/skilldeliver)\n"
#f"<:patreon:707663083866161232> [Support me on Patreon](https://www.patreon.com/vmihov)"
),
inline=False
)
embed.set_thumbnail(url=JUDGE0_ICON)
await ctx.send(embed=embed)
#-------------------------------------------------------------------------------
@commands.hybrid_command(
name="botinfo",
description="Get some useful (or not) information about the bot.",
)
@checks.not_blacklisted()
async def botinfo(self, context: Context) -> None:
mem = psutil.virtual_memory()
pid = os.getpid()
memory_use = psutil.Process(pid).memory_info()[0]
data = [
("Process memory", f"{memory_use / math.pow(1024, 2):.2f}MB"),
("CPU Usage", f"{psutil.cpu_percent()}%"),
("RAM Usage", f"{mem.percent}%"),
]
embed = discord.Embed(
description=":id: GitHUB\n[Die-Antwoord](https://github.com/Die-Antwoord) ",
color=0x9C84EF
)
embed.set_author(
name="Bot Information"
)
embed.add_field(
name=":mortar_board: Bot Owner:",
value="Die Antwoord#1337",
inline=False
)
embed.add_field(
name=":keyboard: Python Version:",
value=f"Python {platform.python_version()}",
inline=True
)
embed.add_field(
name=":pager: OS Version:",
value=(f"Running on: {platform.system()} {platform.release()} ({os.name})"),
inline=True
)
embed.add_field(
name=":computer: System status:",
value="\n".join(f"**{x[0]}** {x[1]}" for x in data),
inline=False
)
embed.add_field(
name=":information_source: Prefix:",
value=f"`/` (Slash Commands)\nor\n`{self.bot.config['prefix']}` for normal commands",
inline=False
)
embed.set_footer(
text=f"Requested by {context.author}\nRequested at {context.guild.created_at}"
)
await context.send(embed=embed)
#-------------------------------------------------------------------------------
# @commands.hybrid_command(
# name="system",
# description="Get some useful (or not) information about the system.",
# )
# #@commands.command(aliases=["status"])
# async def system(self, ctx: commands.Context):
# """Get status of the host system"""
# process_uptime = time.time() - self.bot.start_time
# system_uptime = time.time() - psutil.boot_time()
# mem = psutil.virtual_memory()
# pid = os.getpid()
# memory_use = psutil.Process(pid).memory_info()[0]
# data = [
# ("Bot booted up in", util.stringfromtime(self.bot.boot_up_time)),
# ("Process uptime", util.stringfromtime(process_uptime, 2)),
# ("Process memory", f"{memory_use / math.pow(1024, 2):.2f}MB"),
# ("System uptime", util.stringfromtime(system_uptime, 2)),
# ("CPU Usage", f"{psutil.cpu_percent()}%"),
# ("RAM Usage", f"{mem.percent}%"),
# ]
# content = discord.Embed(
# title=":computer: System status",
# colour=int("5dadec", 16),
# description="\n".join(f"**{x[0]}** {x[1]}" for x in data),
# )
# await ctx.send(embed=content)
#-------------------------------------------------------------------------------
@commands.hybrid_command(
name="serverinfo",
description="Get some useful (or not) information about the server.",
)
@checks.not_blacklisted()
async def serverinfo(self, context: Context) -> None:
roles = [role.mention for role in context.guild.roles]
if len(roles) > 30:
roles = roles[:30]
roles.append (f"Displaying[30/{len(roles)} Roles")
roles = ", ".join(roles)
embed = discord.Embed(
title="**Server Name:**",
description=f"{context.guild}",
color=0x9C84EF
)
if context.guild.icon is not None:
embed.set_thumbnail(
url=context.guild.icon.url
)
embed.add_field(
name="Server ID",
value=context.guild.id,
inline=True
)
embed.add_field(
name="Member Count",
value=context.guild.member_count,
inline=True
)
embed.add_field(
name="Text/Voice Channels",
value=f"{len(context.guild.channels)}",
inline=True
)
embed.add_field(
name=f"Roles ({len(context.guild.roles)})",
value=roles
)
embed.set_footer(
text=f"Created at: {context.guild.created_at}"
)
await context.send(embed=embed)
#-------------------------------------------------------------------------------
@commands.hybrid_command(
name="ping",
description="Check if the bot is alive.",
)
@checks.not_blacklisted()
async def ping(self, context: Context) -> None:
embed = discord.Embed(
title="The bot latency is ",
description=f"**{round(self.bot.latency * 1000)}ms.**",
color=0x9C84EF
)
await context.send(embed=embed)
#-------------------------------------------------------------------------------
@commands.hybrid_command(
name="invite",
description="Get the invite link of the bot to be able to invite it.",
)
@checks.not_blacklisted()
async def invite(self, context: Context) -> None:
embed = discord.Embed(
title="🔑 Permission Administrator",
description=f"Invite me by clicking [here](https://discordapp.com/oauth2/authorize?&client_id={self.bot.config['application_id']}&scope=bot+applications.commands&permissions={self.bot.config['permissions']}).",
color=0xD75BF4
)
try:
# To know what permissions to give to your bot, please see here: https://discordapi.com/permissions.html and remember to not give Administrator permissions.
await context.author.send(embed=embed)
await context.send("I sent you a private message!")
except discord.Forbidden:
await context.send(embed=embed)
#-------------------------------------------------------------------------------
@commands.hybrid_command(
name="server",
description="Get the invite link of the discord server of the bot for some support.",
)
@checks.not_blacklisted()
async def server(self, context: Context) -> None:
embed = discord.Embed(
description=f"Join the support server for the bot by clicking [here](https://discord.gg/ScektXnyBe).",
color=0xD75BF4
)
try:
await context.author.send(embed=embed)
await context.send("I sent you a private message!")
except discord.Forbidden:
await context.send(embed=embed)
#-------------------------------------------------------------------------------
@commands.hybrid_command(
name="8ball",
description="Ask any question to the bot.",
)
@checks.not_blacklisted()
@app_commands.describe(question="The question you want to ask.")
async def eight_ball(self, context: Context, *, question: str) -> None:
answers = ["It is certain.", "It is decidedly so.", "You may rely on it.", "Without a doubt.",
"Yes - definitely.", "As I see, yes.", "Most likely.", "Outlook good.", "Yes.",
"Signs point to yes.", "Reply hazy, try again.", "Ask again later.", "Better not tell you now.",
"Cannot predict now.", "Concentrate and ask again later.", "Don't count on it.", "My reply is no.",
"My sources say no.", "Outlook not so good.", "Very doubtful."]
embed = discord.Embed(
title="**My Answer:**",
description=f"{random.choice(answers)}",
color=0x9C84EF
)
embed.set_footer(
text=f"The question was: {question}"
)
await context.send(embed=embed)
#-------------------------------------------------------------------------------
@commands.hybrid_command(
name="bitcoin",
description="Get the current price of bitcoin.",
)
@checks.not_blacklisted()
async def bitcoin(self, context: Context) -> None:
# This will prevent your bot from stopping everything when doing a web request - see: https://discordpy.readthedocs.io/en/stable/faq.html#how-do-i-make-a-web-request
async with aiohttp.ClientSession() as session:
async with session.get("https://api.coindesk.com/v1/bpi/currentprice/BTC.json") as request:
if request.status == 200:
data = await request.json(
content_type="application/javascript") # For some reason the returned content is of type JavaScript
embed = discord.Embed(
title="Bitcoin price",
description=f"The current price is {data['bpi']['USD']['rate']} :dollar:",
color=0x9C84EF
)
else:
embed = discord.Embed(
title="Error!",
description="There is something wrong with the API, please try again later",
color=0xE02B2B
)
await context.send(embed=embed)
#-------------------------------------------------------------------------------
@commands.hybrid_command(
name="rolecount",
description="Get the current rolecount of the server.",
)
@checks.not_blacklisted()
@checks.is_owner()
async def rolecount(self, context) -> None:
data = format(len(context.guild.roles) - 1)
embed = discord.Embed(
title="Total Group Roles",
description=f"\n**`{data}`**",
color=0x9C84EF
)
embed.set_footer(
text=f"Created at: {context.guild.created_at}"
)
await context.send(embed=embed)
#-------------------------------------------------------------------------------
async def setup(bot):
await bot.add_cog(General(bot))