Skip to content

Commit

Permalink
Merge pull request #7 from ilynivin/Xelyer
Browse files Browse the repository at this point in the history
V6.0.1
  • Loading branch information
ilynivin authored Feb 26, 2025
2 parents 46242b2 + 3a4f9d1 commit 41aa64a
Show file tree
Hide file tree
Showing 9 changed files with 208 additions and 13 deletions.
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,25 @@
<img src='/~https://github.com/ilynivin/Xelyerbot/blob/Xelyer/img/1.png' alt='Meme' width=300px>
</p>

> Eightball Command
<p align='left'>
<img src='/~https://github.com/ilynivin/Xelyerbot/blob/Xelyer/img/3.png' alt='Meme' width=300px>
</p>

> Joke Command
<p align='left'>
<img src='/~https://github.com/ilynivin/Xelyerbot/blob/Xelyer/img/2.png' alt='Meme' width=300px>
</p>

> Slap Command
<p align='left'>
<img src='/~https://github.com/ilynivin/Xelyerbot/blob/Xelyer/img/4.png' alt='Meme' width=300px>
</p>


## Add Xelyer to Your Discord Server 😃

You can easily add Xelyer to your Discord server by clicking on the following link: [Add Xelyer to Your Server](https://discord.com/oauth2/authorize?client_id=1111316333666254878&permissions=534723950656&scope=bot)
Expand Down
33 changes: 20 additions & 13 deletions bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import os
import asyncio
from discord.ext import commands
from discord import app_commands

class MyBot(commands.Bot):
def __init__(self, command_prefix, intents):
Expand All @@ -17,39 +18,45 @@ async def setup_hook(self):
except Exception as e:
print(f'Failed to load extension {extension}: {e}')


await self.tree.sync()
print("Slash commands synced")

async def on_ready(self):
print(f'Logged in as {self.user.name}')
print(f'Bot Ready!')
await self.change_presence(status=discord.Status.idle, activity=discord.Activity(type=discord.ActivityType.listening, name="Github.com/Xelyer|| xy!getstarted"))


async def on_disconnect(self):
print(f'{self.user.name} has disconnected.')


async def on_guild_join(self, guild):
for channel in guild.text_channels:
if channel.permissions_for(guild.me).send_messages:
await channel.send('Hello! I am Xelyer, a simple discord bot. Use `xy!getstarted` to get started with me.')
break
break
else:
await guild.owner.send('I do not have permission to send messages in your server. Please grant me the permission to send messages in a channel to use me. Use `xy!getstarted` to get started with me.')

async def on_reaction_add(self, reaction, user):
if user.bot:
return

if reaction.message.author == self.user and reaction.emoji == '😂':
ctx = await self.get_context(reaction.message)
command = self.get_command('joke')
if command:
await ctx.invoke(command)

if reaction.message.author == self.user and reaction.emoji == '❌':
await reaction.message.delete()
await user.send('I am Sorry looks like this joke is not for you! You can use `!joke` to get a new joke.')

await reaction.message.channel.send(f"{user.mention} Message Deleted")
if reaction.message.author == self.user and reaction.emoji == '🔄':
generator_msg = await reaction.message.channel.send("Please wait! I'm generating your joke ...")
await asyncio.sleep(4)
await generator_msg.delete()
ctx = await self.get_context(reaction.message)
ctx.command = self.get_command('joke')
await self.invoke(ctx)

async def on_command_error(self, ctx, error):
if isinstance(error, commands.CommandNotFound):
await ctx.send("❌ Command not found! Please use a valid command.")
else:
await ctx.send("⚠️ An error occurred! Please try again later.")
print(f"An error occurred: {error}")

intents = discord.Intents.default()
intents.message_content = True
Expand Down
1 change: 1 addition & 0 deletions commands/joke.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ async def joke(self, ctx: commands.Context):
await ctx.send('React with 😂 if you liked the joke and want a new joke or ❌ if you did not like the joke.')
await joke_msg.add_reaction('😂')
await joke_msg.add_reaction('❌')
await joke_msg.add_reaction('🔄')
else:
await joke_msg.edit(content=f"Aww Looks Like this is a Bad Day for Jokes !.{ctx.author.mention}")
except (aiohttp.ClientError, json.JSONDecodeError) as e:
Expand Down
56 changes: 56 additions & 0 deletions commands/rpc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import discord
from discord.ext import commands
from discord import app_commands
import random
import asyncio

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

@commands.command(name='rpc', help='Play Rock Paper Scissors with the bot')
async def rpc(self, ctx: commands.Context):
options = ['rock', 'paper', 'scissors']
bot_choice = random.choice(options)
await ctx.send('🪨📄✂️ Choose Your Weapon: Rock, Paper or Scissors')
await ctx.send('⏳ You have 10 seconds to choose')

def check(m):
return m.author == ctx.author and m.channel == ctx.channel and m.content.lower() in options

try:
user_choice = await self.bot.wait_for('message', check=check, timeout=10)
await ctx.send(f'You chose {user_choice.content} {self.get_emoji(user_choice.content.lower())}')
x = await ctx.send('🔄 I am choosing my weapon...')
await asyncio.sleep(2)
await x.delete()
await ctx.send(f'I chose {bot_choice} {self.get_emoji(bot_choice)}')

if user_choice.content.lower() == bot_choice:
await ctx.send('🤝 It\'s a tie!')
elif (user_choice.content.lower() == 'rock' and bot_choice == 'scissors') or \
(user_choice.content.lower() == 'paper' and bot_choice == 'rock') or \
(user_choice.content.lower() == 'scissors' and bot_choice == 'paper'):
await ctx.send('🎉 You win!')
else:
await ctx.send('😈 I win!')

except asyncio.TimeoutError:
await ctx.send('⏰ You took too long to choose! I win!')

# Any Other Error
except Exception as e:
await ctx.send('⚠️ An error occurred! Please try again later')
print(f"An error occurred in Rpc game: {e}")

def get_emoji(self, choice):
if choice == 'rock':
return '🪨'
elif choice == 'paper':
return '📄'
elif choice == 'scissors':
return '✂️'
return ''

async def setup(bot):
await bot.add_cog(Rpc(bot))
44 changes: 44 additions & 0 deletions commands/status.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import discord
from discord.ext import commands
import datetime

class Status(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.start_time = datetime.datetime.utcnow()

@commands.command(name='latency', help='Shows the bot latency')
async def latency(self, ctx: commands.Context):
latency = self.bot.latency * 1000 # Convert to milliseconds
await ctx.send(f'🏓 Pong! Latency: {latency:.2f}ms')

@commands.command(name='uptime', help='Shows the bot uptime')
async def uptime(self, ctx: commands.Context):
now = datetime.datetime.utcnow()
delta = now - self.start_time
hours, remainder = divmod(int(delta.total_seconds()), 3600)
minutes, seconds = divmod(remainder, 60)
await ctx.send(f'🕒 Uptime: {hours}h {minutes}m {seconds}s')

@commands.command(name='status', help='Shows the bot status')
async def status(self, ctx: commands.Context):
latency = self.bot.latency * 1000 # Convert to milliseconds
now = datetime.datetime.utcnow()
delta = now - self.start_time
hours, remainder = divmod(int(delta.total_seconds()), 3600)
minutes, seconds = divmod(remainder, 60)
server_count = len(self.bot.guilds)
user_count = sum(guild.member_count for guild in self.bot.guilds)

embed = discord.Embed(title="Bot Status", color=discord.Color.blue())
embed.add_field(name="Latency", value=f'{latency:.2f}ms', inline=False)
embed.add_field(name="Uptime", value=f'{hours}h {minutes}m {seconds}s', inline=False)
embed.add_field(name="Servers", value=f'{server_count}', inline=False)
embed.add_field(name="Users", value=f'{user_count}', inline=False)
embed.set_thumbnail(url=self.bot.user.avatar.url)
embed.set_footer(text=f'Requested by {ctx.author}', icon_url=ctx.author.avatar.url)
await ctx.send(embed=embed)

async def setup(bot):
await bot.add_cog(Status(bot))

68 changes: 68 additions & 0 deletions commands/trivia.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import discord
from discord.ext import commands
import aiohttp
import random
import asyncio
import logging


# Configure Logging
logging.basicConfig(level=logging.ERROR,format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

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

@commands.command(name='trivia', help='Starts a trivia game')
async def trivia(self, ctx: commands.Context):
async with aiohttp.ClientSession() as session:
async with session.get("https://opentdb.com/api.php?amount=10&category=15&type=multiple") as response:
if response.status == 200:
data = await response.json()
question = data['results'][0]['question']
correct_answer = data['results'][0]['correct_answer']
incorrect_answers = data['results'][0]['incorrect_answers']
options = incorrect_answers + [correct_answer]
random.shuffle(options)

embed = discord.Embed(
title="🧠 Trivia Time!",
description=question,
color=discord.Color.green()
)
embed.add_field(name="Options", value="\n".join([f"{i+1}. {option}" for i, option in enumerate(options)]), inline=False)
embed.set_footer(text="Reply with the correct option number! 📝")

trivia_msg = await ctx.send(embed=embed)

def check(m):
return m.author == ctx.author and m.channel == ctx.channel

try:
answer = await self.bot.wait_for('message', check=check, timeout=25.5)
if answer.content.lower() == correct_answer.lower():
raise aiohttp.ClientError
await ctx.send(f"🎉 Correct! The answer is {correct_answer}.")

else:
await ctx.send(f"❌ Wrong! The correct answer was {correct_answer}.")

#Exception for Timeout
except asyncio.TimeoutError:
await ctx.send(f"⏰ Time's up! The correct answer was {correct_answer}.")
await ctx.send(f"👽 Better luck next time! , Use ` xy!trivia` to play again.")
#Exception for API errors
except aiohttp.ClientError as ce:
await ctx.send("⚠️ Failed to fetch trivia question. Please try again later.")
await ctx.send("Please Send this error to the developer: `API Error`")
print(f"An API error occurred: {ce}")
# Exception handling for all other exceptions
except Exception as e:
await ctx.send("⚠️ Looks like i encountered an error. Please try again later.")
logging.error(e)
print(f"An unknown Error Occured: {e}")
else:
await ctx.send("⚠️ Failed to fetch trivia question. Please try again later.")

async def setup(bot):
await bot.add_cog(Trivia(bot))
Binary file added img/2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added img/3.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added img/4.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 41aa64a

Please sign in to comment.