OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Discord slash commands with python and failing

  • Thread starter Thread starter Aerialflame7125
  • Start date Start date
A

Aerialflame7125

Guest
I am setting up a discord.py file for a discord bot I have. Everything is going smooth so far, I got messages sending working, but not commands, I started setting it up, but now having issues. I have gone to several other posts, but to no avail.

discordtest.py:

Code:
import requests
import os
import logging
import discord
from discord.ext import commands
from discord_slash import SlashCommand, SlashContext

# Set up logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

intents = discord.Intents.default()
bot = commands.Bot(command_prefix='!',intents=discord.Intents.all())
slash = SlashCommand(bot, sync_commands=True)

DISCORD_TOKEN = 'you thought, lol'
CHANNEL_ID = 'my channel id'

def get_unique_filename(base_name, ext):
    counter = 1
    filename = f"{base_name}.{ext}"
    while os.path.exists(filename):
        filename = f"{base_name}_{counter}.{ext}"
        counter += 1
    return filename

def download_image(url, filename):
    response = requests.get(url, stream=True)
    response.raise_for_status()
    with open(filename, 'wb') as f:
        for chunk in response.iter_content(chunk_size=8192):
            f.write(chunk)
    logging.info(f"Image saved as {filename}")

async def fetch_images(category, ctx):
    try:
        url = f"https://nekosapi.com/api/v3/images/random?category={category}"
        response = requests.get(url)
        response.raise_for_status()

        data = response.json()
        image_url = data['url']  # Adjust this according to the actual JSON response

        filename = get_unique_filename(f"{category}_image", "jpg")
        download_image(image_url, filename)

    except requests.exceptions.RequestException as e:
        logging.error(f"An error occurred while fetching the image: {e}")

async def send_image_to_discord(filename, ctx):
    channel = bot.get_channel(int(CHANNEL_ID))
    if channel:
        await channel.send(file=discord.File(filename))
    else:
        logging.error("Channel not found")

async def send_image_to_user(filename, ctx):
    await ctx.author.send(file=discord.File(filename))

@slash.slash(name="run", description="Fetch images from nekosapi.com", options=[
    {
        "name": "category",
        "description": "The category of images to fetch",
        "type": 3,
        "required": True,
        "choices": [
            {"name": "safe", "value": "safe"},
            {"name": "suggestive", "value": "suggestive"},
        ]
    }
])
async def run_image_downloader(ctx: SlashContext, category: str):
    await ctx.send(content=f"Fetching {category} images...", hidden=True)
    await fetch_images(category.lower(), ctx)

@bot.event
async def on_ready():
    logging.info(f'Logged in as {bot.user.name}')
    logging.info(f'Bot is ready')

if __name__ == "__main__":
    bot.run(DISCORD_TOKEN)

I have changed the "bot = commands.Bot" This bot is supposed to grab images from an api and send them to discord, I am trying to make the bot replies only visible to the message sender, but overall having the same issue.

Code:
Traceback (most recent call last):
  File "C:\Users\colin\OneDrive\Desktop\esrdg\Image API\discordtest.py", line 6, in <module>
    from discord_slash import SlashCommand, SlashContext
ModuleNotFoundError: No module named 'discord_slash'

I have installed "discord-py-slash-command" and "discord.py" yet this is still happening.
<p>I am setting up a discord.py file for a discord bot I have. Everything is going smooth so far, I got messages sending working, but not commands, I started setting it up, but now having issues. I have gone to several other posts, but to no avail.</p>
<p>discordtest.py:</p>
<pre><code>import requests
import os
import logging
import discord
from discord.ext import commands
from discord_slash import SlashCommand, SlashContext

# Set up logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

intents = discord.Intents.default()
bot = commands.Bot(command_prefix='!',intents=discord.Intents.all())
slash = SlashCommand(bot, sync_commands=True)

DISCORD_TOKEN = 'you thought, lol'
CHANNEL_ID = 'my channel id'

def get_unique_filename(base_name, ext):
counter = 1
filename = f"{base_name}.{ext}"
while os.path.exists(filename):
filename = f"{base_name}_{counter}.{ext}"
counter += 1
return filename

def download_image(url, filename):
response = requests.get(url, stream=True)
response.raise_for_status()
with open(filename, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
logging.info(f"Image saved as {filename}")

async def fetch_images(category, ctx):
try:
url = f"https://nekosapi.com/api/v3/images/random?category={category}"
response = requests.get(url)
response.raise_for_status()

data = response.json()
image_url = data['url'] # Adjust this according to the actual JSON response

filename = get_unique_filename(f"{category}_image", "jpg")
download_image(image_url, filename)

except requests.exceptions.RequestException as e:
logging.error(f"An error occurred while fetching the image: {e}")

async def send_image_to_discord(filename, ctx):
channel = bot.get_channel(int(CHANNEL_ID))
if channel:
await channel.send(file=discord.File(filename))
else:
logging.error("Channel not found")

async def send_image_to_user(filename, ctx):
await ctx.author.send(file=discord.File(filename))

@slash.slash(name="run", description="Fetch images from nekosapi.com", options=[
{
"name": "category",
"description": "The category of images to fetch",
"type": 3,
"required": True,
"choices": [
{"name": "safe", "value": "safe"},
{"name": "suggestive", "value": "suggestive"},
]
}
])
async def run_image_downloader(ctx: SlashContext, category: str):
await ctx.send(content=f"Fetching {category} images...", hidden=True)
await fetch_images(category.lower(), ctx)

@bot.event
async def on_ready():
logging.info(f'Logged in as {bot.user.name}')
logging.info(f'Bot is ready')

if __name__ == "__main__":
bot.run(DISCORD_TOKEN)
</code></pre>
<p>I have changed the "bot = commands.Bot" This bot is supposed to grab images from an api and send them to discord, I am trying to make the bot replies only visible to the message sender, but overall having the same issue.</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\colin\OneDrive\Desktop\esrdg\Image API\discordtest.py", line 6, in <module>
from discord_slash import SlashCommand, SlashContext
ModuleNotFoundError: No module named 'discord_slash'
</code></pre>
<p>I have installed "discord-py-slash-command" and "discord.py" yet this is still happening.</p>
 

Latest posts

I
Replies
0
Views
1
Isaac P. Liu
I
U
Replies
0
Views
1
user3658366
U
G
Replies
0
Views
1
Giampaolo Levorato
G
M
Replies
0
Views
1
Marcelo Rodrigo Nascimento
M
Top