Spaces:
Paused
Paused
File size: 11,315 Bytes
f5902c7 1a26fbe f5902c7 7298f29 f5902c7 13b8c1f f5902c7 6c0d1fd f5902c7 421cf0e f5902c7 bfd36b9 a61547a 91d4bc6 a61547a f5902c7 81d6724 0b418d5 a138f4d 153791e 13b8c1f 97e83bb 1a26fbe 44fa152 c3821ba 44fa152 bfd36b9 44fa152 6c0d1fd bfd36b9 6c0d1fd 44fa152 bfd36b9 c56b1c0 1a26fbe f5902c7 bfd36b9 f5902c7 9cc3cb7 99d64f1 f5902c7 0066b5e f425c62 0066b5e f425c62 0066b5e f5902c7 fad9ee0 f5902c7 fad9ee0 7ccf044 fad9ee0 f5902c7 c749a32 f5902c7 c749a32 fad9ee0 f425c62 9cc3cb7 f425c62 b2b80c2 0066b5e f5902c7 0066b5e f5902c7 421cf0e f5902c7 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 |
import asyncio
import os
import threading
from threading import Event
from typing import Optional
import datetime
import requests
import discord
import gradio as gr
from gradio_client import Client
from discord import Permissions
from discord.ext import commands
from discord.utils import oauth_url
from gradio_client.utils import QueueError
import base64
event = Event()
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
HF_TOKEN = os.getenv("HF_TOKEN")
API_URL = "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-xl-base-1.0"
headers = {"Authorization": "Bearer " + HF_TOKEN}
def ask(input_text):
api_url = "https://somerandomapifor-disorc-cause-i-need-it.onrender.com/qa"
params = {'question': input_text}
response = requests.get(api_url, params=params)
if response.status_code == 200:
json_response = response.json()
answer = json_response.get('answer') # Assuming the JSON response has an 'answer' field
# Applying the operation to the answer
modified_answer = answer[:-4] if answer else "No answer found."
return modified_answer
else:
return "Error: Unable to fetch response"
async def wait(job):
while not job.done():
await asyncio.sleep(0.2)
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="$", intents=intents, help_command=None)
@bot.command()
async def uptime(ctx):
"""Displays the uptime of the bot."""
delta = datetime.datetime.utcnow() - bot.start_time
hours, remainder = divmod(int(delta.total_seconds()), 3600)
minutes, seconds = divmod(remainder, 60)
days, hours = divmod(hours, 24)
# Create a fancy embed with emojis
embed = discord.Embed(title="Bot Uptime", color=discord.Color.green())
embed.add_field(name="Uptime", value=f"{days} days, {hours} hours, {minutes} minutes, {seconds} seconds", inline=False)
embed.set_footer(text="Created by Cosmos")
await ctx.send(embed=embed)
@bot.command()
async def ai(ctx, *, input_text: str):
"""Ask our AI model a question."""
async with ctx.typing():
result = ask(input_text)
# Reply with the embed
await ctx.send(result)
def query(prompt):
payload = prompt
response = requests.post(API_URL, headers=headers, json=payload)
return response.content
@bot.command()
async def img(ctx, *, prompt: str):
# Query the API to generate the image
async with ctx.typing():
image_data = query(prompt)
# Encode image data as base64
image_b64 = base64.b64encode(image_data).decode('utf-8')
# Send the image as a file
await ctx.send(file=discord.File(base64.b64decode(image_b64), filename="generated_image.png"))
@bot.command()
async def verse(ctx):
"""Get a random Bible verse."""
# Fetch a random Bible verse
bible_api_url = "https://labs.bible.org/api/?passage=random&type=json"
response = requests.get(bible_api_url)
if response.status_code == 200:
verse = response.json()[0]
passage = f"**{verse['bookname']} {verse['chapter']}:{verse['verse']}** \n{verse['text']}"
else:
passage = "Unable to fetch Bible verse"
# Create an embed
embed = discord.Embed(title="Random Bible Verse", description=passage, color=discord.Color.blue())
embed.set_footer(text="Created by Cosmos")
await ctx.send(embed=embed)
@bot.command()
@commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, reason: Optional[str] = "No reason provided"):
"""Kicks a member."""
try:
await member.kick(reason=reason)
await ctx.send(f"{member.mention} has been kicked. Reason: {reason}")
except discord.Forbidden:
await ctx.send("I don't have permission to kick members.")
except discord.HTTPException:
await ctx.send("An error occurred while trying to kick the member. Please try again later.")
@bot.command()
@commands.has_permissions(ban_members=True)
async def ban(ctx, member: discord.Member, *, reason: Optional[str] = "No reason provided"):
"""Bans a member."""
try:
await member.ban(reason=reason)
await ctx.send(f"{member.mention} has been banned. Reason: {reason}")
except discord.Forbidden:
await ctx.send("I don't have permission to ban members.")
except discord.HTTPException:
await ctx.send("An error occurred while trying to ban the member. Please try again later.")
@bot.command()
async def cmds(ctx):
"""Returns a list of commands and bot information."""
# Get list of commands
command_list = [f"{command.name}: {command.help}" for command in bot.commands]
# Get bot information
bot_info = f"Bot Name: {bot.user.name}\nBot ID: {bot.user.id}"
# Create an embed
embed = discord.Embed(title="Bot prefix: $", color=discord.Color.blue())
embed.add_field(name="Commands", value="\n".join(command_list), inline=False)
embed.add_field(name="Bot Information", value=bot_info, inline=False)
embed.set_footer(text="Created by Cosmos")
await ctx.send(embed=embed)
async def update_status():
await bot.wait_until_ready() # Wait until the bot is fully ready
while True:
# Fetch the number of members in all guilds the bot is connected to
member_count = sum(guild.member_count for guild in bot.guilds)
# Update the bot's status
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f"{member_count} users"))
# Wait for 60 seconds before updating again
await asyncio.sleep(60)
@bot.event
async def on_ready():
bot.start_time = datetime.datetime.utcnow()
print(f"Logged in as {bot.user} (ID: {bot.user.id})")
event.set()
print("------")
bot.loop.create_task(update_status()) # Create the task within the on_ready event
@bot.event
async def on_member_join(member):
# Fetch the channels by their IDs
channel_ids = [1210566384267034644, 1210987054658494477, 1210578060164866128]
channels_info = []
for channel_id in channel_ids:
channel = member.guild.get_channel(channel_id)
if channel:
channels_info.append(f"• {channel.name}: {channel.mention}")
# Prepare the message content
channels_message = "\n".join(channels_info)
message_content = (
f"Welcome to the server, {member.name}!\n\n"
f"Hope you have a great stay here, {member.mention}!\n\n"
f"Here are some channels you might find interesting:\n{channels_message}\n\n"
)
# Fetch a random Bible verse
bible_api_url = "https://labs.bible.org/api/?passage=random&type=json"
response = requests.get(bible_api_url)
if response.status_code == 200:
verse = response.json()[0]
passage = f"{verse['bookname']} {verse['chapter']}:{verse['verse']} - {verse['text']}"
# Include the Bible verse in the message content
message_content += f"\n\nRandom Bible Verse:\n{passage}"
else:
passage = "Unable to fetch Bible verse"
# Send a direct message to the user with the message content including the Bible verse
try:
await member.send(message_content)
except discord.HTTPException:
print(f"Failed to send a DM to {member.name}")
# Create an embed for the welcome channel
welcome_channel = discord.utils.get(member.guild.channels, name="👋wellcome-goodbye")
if welcome_channel:
embed = discord.Embed(
title=f"Welcome to the server, {member.name}!",
description=f"Hope you have a great stay here, {member.mention}!",
color=discord.Color.blue()
)
embed.add_field(name="Random Bible Verse", value=passage, inline=False)
embed.set_footer(text="Created by Cosmos")
await welcome_channel.send(embed=embed)
@bot.command()
async def search(ctx, *, query: str):
"""Search for a bible verse."""
bible_api_url = f"https://labs.bible.org/api/?passage={query}&type=json"
response = requests.get(bible_api_url)
if response.status_code == 200:
verses = response.json()
if verses:
# If verses are found, concatenate them into a single message
passage = "\n".join(f"**{verse['bookname']} {verse['chapter']}:{verse['verse']}** \n{verse['text']}" for verse in verses)
passage = truncate_response(passage)
embed = discord.Embed(title=f"Search Results for '{query}'", description=passage, color=discord.Color.blue())
else:
embed = discord.Embed(title="Search Results", description="No results found.", color=discord.Color.red())
else:
embed = discord.Embed(title="Search Results", description="Unable to fetch search results.", color=discord.Color.red())
embed.set_footer(text="Created by Cosmos")
await ctx.send(embed=embed)
@bot.command()
@commands.has_permissions(manage_messages=True)
async def purge(ctx, limit: int):
"""Removes N amount of messages."""
try:
await ctx.channel.purge(limit=limit + 1) # Add 1 to include the command message itself
await ctx.send(f"{limit} messages have been purged.")
except discord.Forbidden:
await ctx.send("I don't have permission to manage messages.")
except discord.HTTPException:
await ctx.send("An error occurred while trying to purge messages. Please try again later.")
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
await ctx.send("Sorry, I couldn't find that command. Use `$cmds` to see the list of available commands.")
elif isinstance(error, commands.MissingRequiredArgument):
await ctx.send("Oops! Looks like you're missing some required arguments.")
elif isinstance(error, commands.CheckFailure):
await ctx.send("You do not have the permissions to execute this command.")
else:
# Log the error to console or your logging system
print(f"An error occurred: {error}")
# Additional error handling for unexpected errors
@bot.event
async def on_error(event_method, *args, **kwargs):
# Log the error to console or your logging system
print(f"An error occurred in {event_method}: {sys.exc_info()}")
# Error handling for unhandled exceptions
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandInvokeError):
original_error = error.original
if isinstance(original_error, discord.Forbidden):
await ctx.send("I don't have permissions to do that.")
elif isinstance(original_error, discord.HTTPException):
await ctx.send("An error occurred while processing the command. Please try again later.")
else:
# Log the error to console or your logging system
print(f"Error: {original_error}")
await ctx.send("An unexpected error occurred.")
# running in thread
def run_bot():
if not DISCORD_TOKEN:
print("DISCORD_TOKEN NOT SET")
event.set()
else:
bot.run(DISCORD_TOKEN)
threading.Thread(target=run_bot).start()
event.wait()
with gr.Blocks() as demo:
gr.Markdown(
f"""
# Discord bot is online!
"""
)
demo.launch() |