#discord-bots

1 messages · Page 340 of 1

wispy pasture
#

fixed that error ages ago, got a new error:

2024-02-06 23:01:27 ERROR    discord.ui.view Ignoring exception in view <PingView timeout=180.0 children=1> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='Stop it' emoji=None row=None>
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/ui/view.py", line 427, in _scheduled_task
    await item.callback(interaction)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: PingView.stop_button_callback() missing 1 required positional argument: 'interaction'```

and code:
https://srcb.in/ijQxKiBp9l
tiny coyote
#

well yh I created the command cooldown:

    @commands.cooldown(1,120,commands.BucketType.user)
    @commands.command()

then i made a variable for how much time user has after using the command

 bot.cd = {}
            if message.author.id not in bot.cd:
                bot.cd[message.author.id] = {"F":"✔", "M":"✔", "C":"✔"}
                print(f"{user} is the given attribute")
cloud dawn
tiny coyote
cloud dawn
#

The cooldown, when it's up it gives a CommandOnCooldown error.

tiny coyote
#

well I wanted to make a cooldown command that shows every command timer at once, so the user doesnt have to spam every command to know whats off cooldown or not

#

and personally idk how to use error..

slate swan
#

what wrapper should I use?

tiny coyote
#

like the rpg bot !cooldown command.. or something similar

slate swan
#

Like I think I'm ready to learn bots

cloud dawn
slate swan
cloud dawn
#

Or Hikari if youré up for a challange.

wispy pasture
#

error:

2024-02-06 23:08:04 ERROR    discord.ui.view Ignoring exception in view <PingView timeout=180.0 children=1> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='Stop it' emoji=None row=None>
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/ui/view.py", line 427, in _scheduled_task
    await item.callback(interaction)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: PingView.stop_button_callback() missing 1 required positional argument: 'button'```

code:
https://srcb.in/PJEl1ZkorI
cloud dawn
tiny coyote
#

like?

cloud dawn
#

You could use something like this ->

#

Event that only triggers on successful command, you'd still need to track it... but now it's a bit easier to manage.

wispy pasture
cloud dawn
wispy pasture
#

okay so i have this error before and i know what is causing it, but i cant recall a way to fix it

An error occurred: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.1.custom_id: Component custom id cannot be duplicated```
#

lemme try custom_id parameters

#

nvm

wispy pasture
#

error:

Traceback (most recent call last):
  File "/home/container/main.py", line 284, in ping
    message = await ctx.send(f"### Pong! 🏓 \n> **Latency:** {latency:.2f} ms \n> **Uptime:** {uptime_str} \n", view=view)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/context.py", line 1060, in send
    await self.interaction.response.send_message(**kwargs)
  File "/home/container/.local/lib/python3.11/site-packages/discord/interactions.py", line 801, in send_message
    await adapter.create_interaction_response(
  File "/home/container/.local/lib/python3.11/site-packages/discord/webhook/async_.py", line 221, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.1.custom_id: Component custom id cannot be duplicated```

code:
https://srcb.in/Z7ThFcrRhb
golden portal
#

from the looks of it just use the decorator one, you dont have to create another stop button

wispy pasture
#

aha, well i fixed that

#

Traceback (most recent call last):
File "/home/container/main.py", line 298, in ping
await ctx.send(f"### Pong! 🏓 \n> Latency: {latency:.2f} ms \n> Uptime: {uptime_str} \n", view=view)
File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/context.py", line 1060, in send
await self.interaction.response.send_message(**kwargs)
File "/home/container/.local/lib/python3.11/site-packages/discord/interactions.py", line 801, in send_message
await adapter.create_interaction_response(
File "/home/container/.local/lib/python3.11/site-packages/discord/webhook/async_.py", line 221, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.4.label: This field is required

novel bone
#

ok idk where to put this in but its for discord but im attempts to make something where its for a cf betting system but like im convinced their code has patterns that actually profit so its to copy the command depending on if you put w or l i have most of the code im just wondering if someone could help me since I cant seem to get the ui im trying to make to work. I will say that I had chat gpt help me like heavily for this and its just past the character limit so its prob super easy to solve im just kinda stupid

#

idk if someone could dm me to help or if it has to be done here or what

#

just really need some help

drifting arrow
#
    @button(label="Timeout User", style=ButtonStyle.red, row=0)
    async def timeout_user_button(self, interaction: Interaction, button: Button):
        button = await self.change_button(button)
        original_message:Message = interaction.message
        self.timeout_user = not self.timeout_user
        
        timeoutmodal = mm.TimeoutTime()
        self.timeout_time = await interaction.response.send_modal(timeoutmodal)
        
        await interaction.response.defer(ephemeral=True)
        embed = await self.message_embed()
        await original_message.edit(embed=embed, view=self)
``` 🤔 
I want a modal to be sent and the response from that modal to affect the response.
#

Anybody able to help?

hushed galleon
drifting arrow
#

well.

#

dang. my solution was to just parse everything through the modal XD

#

Didnt work anyway

hushed galleon
#

that seems about right if its an ephemeral message, but wouldnt response.edit_message() work instead? (edit: it does work)

drifting arrow
#

it's an ephemeral message

hushed galleon
#

in general, if you want to edit ephemeral messages you need the interaction that sent the message so you can do await interaction.edit_original_response(...) or message = await interaction.original_response(); await message.edit(...)

drifting arrow
#

oh

#

i can pass the original interaction instead lol

hushed galleon
#

not sure if interactions that edit an ephemeral message with edit_message() can also be used in the same way (edit: this also works)

drifting arrow
#

¯_(ツ)_/¯

#

lets find out!

hushed galleon
#

regardless i suggest trying edit_message() inside your modal submit first, if that doesnt work then use edit_original_response() from the button's interaction

drifting arrow
#
    async def on_submit(self, interaction: Interaction):
        self.settings['timeout_time'] = self.timeout_time.value
        embed = await create_settings_embed(**self.settings)
        await self.original_interaction.edit_original_response(embed=embed, view=self.view)
        return self.timeout_time.value
``` :D
#

this works

#

Now to duplicate this and fix the errors I put in place to make this work and we're off to the races!

#

The space races. None of this regular human races.

hushed galleon
#

err, you're not responding to the modal's interaction so i expect it to just say it failed

unkempt canyonBOT
#

discord/ui/modal.py line 188

await self.on_submit(interaction)```
drifting arrow
#
class TimeoutTime(Modal, title='Timeout Duration'):
    def __init__(self, original_interaction, view, settings):
        super().__init__()

        self.original_interaction:Interaction = original_interaction
        self.view = view
        self.settings = settings

    timeout_time = TextInput(
        label='Timeout Time (minutes)',
        style=TextStyle.short,
        placeholder="100",
        required=True,
    )
    
    async def on_submit(self, interaction: Interaction):
        self.settings['timeout_time'] = self.timeout_time.value
        embed = await create_settings_embed(**self.settings)
        await self.original_interaction.edit_original_response(embed=embed, view=self.view)
        await interaction.response.send_message(f"Set timeout time to be: {self.timeout_time.value}", ephemeral=True)
``` whole modal
#

Don't need to return if we can just overrwrite the original stuff \o/

novel bone
#

I need to combine the top part and bottom part because the logic for wins and logic in the ui isnt there

#

I can show the version without the ui if that helps

#

thats without the ui

quick gust
#

can I have separator lines in embeds? I saw a bot having them, but --- doesnt work

#

the little line above "published"

drifting arrow
#

What are the requirements to use animated pictures on my bot?

drifting arrow
formal basin
#

does uptimerobot have an API

glossy ruin
naive briar
# glossy ruin

Their BotBase's setup_hook probably have something to do

glossy ruin
naive briar
#

Python Discord

quick gust
#

they were just using an invisible image, silly little trick

reef basalt
#

can anyone tell what is the problem here

shrewd apex
#
  • specify intents
  • make sure package is installed
reef basalt
open sail
#

I got this security alert on github

#

Does anyone know how to address this problem? thanks~

shrewd apex
reef basalt
balmy crane
#

;p

slate swan
open sail
#

So I was wondering that has anyone else seen this problem before

naive briar
#

People usually use aiohttp if they want to make HTTP requests in their discord.py projects

#

So, not likely

sweet minnow
#

When testing my discord python bot (same server, same perms). All slash commands works perfectly for my account, but when I use an alt account to test, it shows "Application Does Not Respond" error. Why and how to fix?

Account 1:

#

Account 2:

#

Both users are in same server, and both user has the administrator permission.

#

But on account 2, if I run any slash commands (FROM ANOTHER BOT) it works perfectly fine.

naive briar
#

That's likely a problem from the command's code, can you share some of it?

sweet minnow
#

the host port user password database is all filled in correctly*

connection = mysql.connector.connect(
  host="",
  port="",
  user="",
  password=",
  database=""
)

cursor = connection.cursor()
cursor.execute("SET SESSION wait_timeout = 1209600")  # Set wait_timeout to 14 days
cursor.execute("SET SESSION interactive_timeout = 1209600")  # Set interactive_timeout to 14 days

# Create tables if they don't exist
cursor.execute("CREATE TABLE IF NOT EXISTS balances (user_id BIGINT PRIMARY KEY, balance BIGINT)")

cursor.execute("CREATE TABLE IF NOT EXISTS items (item_name VARCHAR(255), price BIGINT, amount BIGINT DEFAULT 0)")

cursor.execute("CREATE TABLE IF NOT EXISTS inventory (user_id BIGINT, item_name VARCHAR(255), itemamount BIGINT DEFAULT 0, PRIMARY KEY (user_id, item_name))")

cursor.execute("SELECT COUNT(*) FROM information_schema.statistics WHERE table_name='inventory' AND index_name='idx_inventory'")

if cursor.fetchone()[0] == 0:
    cursor.execute("CREATE UNIQUE INDEX idx_inventory ON inventory (user_id, item_name)")

#
#balance
def handle_balance(user_id: int) -> int:
    cursor.execute("SELECT balance FROM balances WHERE user_id = %s", (user_id,))
    result = cursor.fetchone()
    if result is None:
        cursor.execute("INSERT INTO balances (user_id, balance) VALUES (%s, %s)", (user_id, 0))
        connection.commit()
        return 0
    return result[0]
#
@bot.slash_command(name="balance", description="View your balance or another user's balance!")
async def balance(ctx, userid: Option(str, "Input the userid of the balance you want to view (optional)", required=False)):
    #check if user specified userid or not
    if userid is None:
        #view own balance
        cursor.execute("SELECT balance FROM balances WHERE user_id=%s", (ctx.author.id,))
        balance = cursor.fetchone()
        if balance is None:
            em = discord.Embed(title="Error", description="You do not have a balance yet.")
            em.set_footer(icon_url = ctx.author.avatar, text=f"Invoked by {ctx.author.name}")
        else:
            em = discord.Embed(title="Your Balance is:", description=f"Your current balance is {balance[0]} SparklyCoins.")
            em.set_footer(icon_url = ctx.author.avatar, text=f"Invoked by {ctx.author.name}")
    else:
        #view another user's balance
        cursor.execute("SELECT balance FROM balances WHERE user_id=%s", (userid,))
        balance = cursor.fetchone()
        if balance is None:
            em = discord.Embed(title="Error", description=f"User <@{userid}> does not have a balance yet.")
            em.set_footer(icon_url = ctx.author.avatar, text=f"Invoked by {ctx.author.name}")
        else:
            em = discord.Embed(title="Your Balance is:", description=f"<@{userid}>'s current balance is {balance[0]} SparklyCoins.")
            em.set_footer(icon_url = ctx.author.avatar, text=f"Invoked by {ctx.author.name}")

    await ctx.respond(embed=em)

    #bot tips
    em = discord.Embed(title="Tips (PLEASE READ)", description=f"TIP: {random.choice(bottips)}")
    await ctx.respond(embed=em, ephemeral=True)
sweet minnow
sweet minnow
#

So what's the issue here? :c

sweet minnow
quick gust
#

ah idk anything about pycord's usage

mighty pilot
#
@bot.event
async def on_message(message):
    if bot.user.mentioned_in(message):
        embed = discord.Embed(description='Default prefix is ","\n",help" for more.')
        await message.channel.send(embed=embed)

    await bot.process_commands(message)```
Bot doesn't send anything when i mention it. What is wrong?
hot sparrow
mighty pilot
#

yes my bot is online and there is no error messages.

hot sparrow
#

i think you meant bot.mentioned_in

formal basin
#

how do i run a flask if i have cogs

unkempt canyonBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

shrewd fjord
cloud dawn
#

@sweet minnowIt's best to use async code when interacting with the database.

somber sky
#

how do you edit the ... placeholder on a slash command arg

thin raft
#

description?

torn solar
slate swan
#

Modal

#

!d discord.ui.Modal

unkempt canyonBOT
#

class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.

This object must be inherited to create a modal popup window within discord.

New in version 2.0.

Examples...
somber sky
#

everytime the bot restarts does the slash command id change? because at first the id started with 105 and now it starts with 120, or is it by server?

slate swan
#

It may differ when you change something with the command but not sure

drifting arrow
hushed galleon
#

also numpy/google/sphinx-style docstrings work too (source code for reference) ```py
@tree.command()
async def my_command(interaction, thingy: str):
"""This is my command!

:param thingy: The thingy to do another thingy

"""
await interaction.response.send_message(f"I'm doing the {thingy} for another thingy")```
unkempt canyonBOT
#
Did you mean ...

» identity
» iterate-dict

faint rapids
naive briar
#

Ok

faint rapids
#

what 💀

vestal acorn
vale wing
young heart
#

is there any free hosting for bots that can host 24/7?

rugged shadow
#

free? yes
good? no

left dew
#

why wont this remove the user from the databse?

@bot.command()
@commands.cooldown(1, 2, commands.BucketType.guild)
async def loa(ctx, userID=None, amt_time=None):
    con,cur = openCON()
    cur.execute(f"SELECT * FROM loa_logs")
    alldata = cur.fetchall()
    support = ctx.guild.get_role(SUPPORT_ID)
    if support in ctx.author.roles:
        if userID is None or amt_time is None:
            await ctx.reply(f"Invalid usage.\n*`usage: {PREFIX} userID time in days`*")
            return
        user_exists = False
        for row in alldata:
            if row["userID"] == userID:
                user_exists = True
                break
            
        if user_exists:
          cur.execute("DELETE FROM loa_logs WHERE userID = %s", (userID,))
          await ctx.reply(f"**Successfully** removed <@{str(userID)}> from the **database**.")
        else:
            con,cur = openCON()
            cur.execute("INSERT INTO loa_logs (userID, timeD) VALUES (%s, %s)", (userID, amt_time))
            con.commit()
            await ctx.reply(f"**Successfully** added <@{str(userID)}> to the **LOA database**.")```
#

i get no errors

naive briar
#

You need to commit the changes to actually make changes

shrewd fjord
thin raft
#

How can I disable the view of a message?

#

Im trying to do it inside the on_timeout

#

but for being able to disable it I need access to the message

hushed galleon
# thin raft How can I disable the view of a message?

you can store the message inside the view after you've sent it, i.e. py view = MyView() view.message = await ctx.send(...) # or for interactions, use .original_response() usually for convenience, i write a view start() method to do this

thin raft
#

thanks

outer needle
#

super new to this (python) and working on a bot, I am not the server owner but i want to restrict the use of some of the commands to just me. i know how to do it for the server owner but as im not the server owner of the intended server, i would like to restrict some commands to just me. curious why this doesnt work:

     return ctx.author.id == ctx.user.id("151480514199552000")

    @bot.command()
    @commands.check(is_owner)
    @commands.check(is_user)
    async def say(ctx, what = "WHAT?"):
            await ctx.send(what)

    @say.error
    async def say_error(ctx, error):
         if isinstance(error, commands.CommandError):
              await ctx.send("Permission Denied") ```
cloud dawn
outer needle
#

i will try that thank you

cloud dawn
#

@outer needle ctx.user.id("151480514199552000") this doesn't make sense and will never be true because ctx.author.id will always return an int. You also can't call an attribute.

outer needle
#

ya i mean im new to this whole thing, im following a general guide and trying to adapt things to more of how i want them. return ctx.author.id == 151480514199552000 this didnt seem to work. things are correctly indented afaik because i have the same code to allow just the server owner to use the commands and that is confirmed working

cloud dawn
#

Can you send what you have right now?

outer needle
#

sure

cloud dawn
#

And owner does work..?

outer needle
#

yes it does

cloud dawn
#

I assume you want the owner and user to be seperate?

outer needle
#

yes the bot is intended for a server that i am not the owner of, but i still want to restrict certain commands (obviously not this one, this is just a test) to the bot owner (me)

cloud dawn
#

Alright, to be honest no clue why this wouldn't work. I could work my own solution with decorators if you'd like, I will link to the docs ofcourse.

outer needle
#

i mean its not super pressing and honestly i can just comment it out for now. bot isnt even close to being finished so its not super important rn. i just thought i could figure it out myself lmao

cloud dawn
#
import settings
import discord
from discord.ext import commands

logger = settings.logging.getLogger("bot")

def is_me():
    def predicate(ctx):
        return ctx.message.author.id == 151480514199552000
    return commands.check(predicate)
    
def is_guild_owner():
    def predicate(ctx):
        return ctx.guild is not None and ctx.guild.owner_id == ctx.author.id
    return commands.check(predicate)

def run():
    intents = discord.Intents.default()
    intents.message_content = True

    bot = commands.Bot(command_prefix="?", intents=intents)

    @bot.event
    async def on_ready():
        logger.info(f"User: {bot.user} (ID: {bot.user.id})")
    
    @bot.command()
    @commands.check_any(is_guild_owner(), is_me())
    async def say(ctx, what = "WHAT?"):
            await ctx.send(what)

    @say.error
    async def say_error(ctx, error):
         if isinstance(error, commands.CommandError):
              await ctx.send("Permission Denied")

    bot.run(settings.DISCORD_API_SECRET, root_logger=True)

if __name__ == "__main__":
    run()
#

And this also takes into account if a command is sent trough DM.

#

Aka not crash.

outer needle
#

is that what predicate does?

cloud dawn
#

Well predicate is bound to the value returned by the decorator.

#

It allows you to do this -> ```py
def is_me():
def predicate(ctx):
return ctx.message.author.id == 85309593344815104
return commands.check(predicate)

@bot.command()
@is_me()
async def only_me(ctx):
await ctx.send('Only you!')

#

So you don't need an extra call what you were doing before @commands.check(is_user) but now just use it directly.

#

Imo also more flexible

outer needle
#

oh wow nice so on any command i can just do @is_me() and it will restrict access to just me?

cloud dawn
#

If the id in is_me is matching to you, yes.

outer needle
#

wow perfect thank you

cloud dawn
pale zenith
#

was literally about to say lol

#

@commands.is_owner() seems far better for this

cloud dawn
#

is_owner meaning the bot owner if set in the bot/client constructor.

#

@outer needle I also now know why yours didn't work before lol

outer needle
#

oh okay

cloud dawn
#

If there are multiple checks like you had before ```py
@commands.check(is_owner)
@commands.check(is_user)

outer needle
#

oooooh okay

#

that makes sense. sorry im not super well versed in this stuff. im like a week into learning python and im trying to do things that are probably a bit out of my realm of knowledge but i like seeing the bot come along

cloud dawn
#

You're doing fine! Just takes time.

flat pier
torn solar
#

is there a limit to how big modals can be

#

like how many questions

golden portal
quick gust
#

I wanna add a check to all my slash commands except one. Do I really have to add the decorator to all of them or is there a way I can exclude the one command from add_app_command_check

vale wing
quick gust
#

well it adds the check globally

vale wing
#

Include a conditional into the check then

quick gust
#

alright yeah thanks

#

wait is that possible tho? how will I know what command ran the check? nvm I think the check function takes a ctx argument

slate swan
#

@slate swan

#

still alive?

vague zephyr
#

this is a simple py @commands.slash_command(name="getkey", description="Generate a user key") async def getkey(ctx: discord.ApplicationContext): await ctx.respond(f"Your key is: {uuid.uuid4()}") but it's not loading on my server

#

is there a reason why

shrewd apex
#

did you sync?

#

which library is this?

vague zephyr
vague zephyr
naive briar
#

Sounds about right

vague zephyr
latent jay
#

@commands.has_permissions() is used to require command invoker to have a certain permission right?

blazing condor
#

!d discord.ext.commands.has_permissions

unkempt canyonBOT
#

@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) that is added that checks if the member has all of the permissions necessary.

Note that this check operates on the current channel permissions, not the guild wide permissions.

The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions).

This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingPermissions) that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure).
vague zephyr
#

This interaction has already been responded to before anyone knows why this is occuring (im using discordpy)

vocal snow
vague zephyr
slate swan
molten spruce
#

I have probleme

#

I have a problem with my bot

strange crater
#

how can i download py-cord?

vestal acorn
vestal acorn
strange crater
#

i just wanna install pycord

#

error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ this could be the problem

vestal acorn
#

ah

#

which version of python do you use?

strange crater
#

3.12

vestal acorn
#

ok

#

you need to downgrade to 3.11

strange crater
#

why?

vestal acorn
#

3.12 doesn't support aiohttp

strange crater
#

oh

vestal acorn
strange crater
#

do i have to uninstall?

vestal acorn
#

yes

strange crater
#

3.11.8?

vestal acorn
#

for example

glad cradle
drifting arrow
#

Alright. What the heck

    theventtypes = [
        Choice(name="PlayerJoin", value="join_event_channel"),
        Choice(name="PlayerLeave", value="leave_event_channel"),
        Choice(name="Triggers", value="trigger_event_channel"),
        Choice(name="Errors", value="errors_channel"),
        Choice(name="AdminLogs", value="admin_log_channel"),
        Choice(name="DefaultChannel", value="default_channel"),
        ]
        
    @command(name="setlogchannel", description="Sets a channel for a designated event type")
    @guild_only()
    @has_any_role(*roles)
    @choices(EventOption=[*theventtypes])
    @describe(EventOption="Which activity logs event type do you want to target?")
    @describe(logchannel="What channel do you want the logs to go to?")
    async def setlogchannel(self, interaction: Interaction, EventOption: Choice[str], logchannel:TextChannel):
        event_name = EventOption.name
        event_value = EventOption.value
        self.config['cogs']['websocket'][event_value] = logchannel.id
        await self.update_config(self.config)
        await interaction.response.send_message(f"Updated '{event_name}' event to be sent to {logchannel.mention}", ephemeral=True)
#
Traceback (most recent call last):
  File "C:\Python311\Lib\site-packages\discord\client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\Declan\Desktop\discordbots\Gnomeslayers Whitelister\Discordbot.py", line 27, in on_ready
    await self.tree.sync()
  File "C:\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1072, in sync
    raise CommandSyncFailure(e, commands) from None
discord.app_commands.errors.CommandSyncFailure: Failed to upload commands to Discord (HTTP status 400, error code 50035)
In command 'setlogchannel' defined in function 'WebsocketManager.setlogchannel'
  In parameter 'EventOption'
    name: Command name is invalid
``` ;-;
#

oh

#

it needed to be lowercase lol

zenith yarrow
#

Can u create a discord bot using py on mobile?
Yes I don't have a pc

robust fulcrum
#

You may need to learn about linux and terminals

zenith yarrow
#

Ik about terminals it's just like console in js

robust fulcrum
#

Sorry I mean shells not terminals

zenith yarrow
#

I don't know shells

robust fulcrum
#

Then you need to learn ,

#

Use termux for running a shell on Android and install python on it and use editor like vim for editing and running discord bot

zenith yarrow
#

I've just started py

robust fulcrum
zenith yarrow
robust fulcrum
#

Learn python properly first

zenith yarrow
#

I'm learning py just to create bots

robust fulcrum
#

I not mean to be rude , but it's a harsh truth

#

It's really bad idea to jumping into discord.py before learning python first

zenith yarrow
#

I see haha i just know very basics of py

robust fulcrum
#

Ye that's problem, cause discord.py requires you to know advanced python topics like async programming

zenith yarrow
#

I see thank you do you have any roadmap for me i just want to create discord bots with py

robust fulcrum
#

Roadmap for learning python?

upbeat otter
#

like OOPs (especially)

zenith yarrow
zenith yarrow
slate swan
zenith yarrow
limpid veldt
#

yo

#

i got a problem

slate swan
#

what is it?

limpid veldt
#

import discord
from discord.ext import commands

def run():
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='.' , intents=intents)
bot.run(BOT_TOKEN')
@bot.event
async def on_ready():
pass

@bot.command()
async def ping(ctx):
    await ctx.send("pong")

if name == 'main':
run()

#

i get an error saying command ping not found

slate swan
#

Oh man..

limpid veldt
#

What

slate swan
#

is there any reason to have your whole logic inside of
a function?

limpid veldt
#

so you saying if i removed the function 'run' it would work ?

slate swan
#

not yet

#

You have to place bot.run() inside of if __name__ == __main__

limpid veldt
#

alright

slate swan
#

also you misspelled the event name called on_ready

limpid veldt
#

okay

limpid veldt
slate swan
#

👍

drifting arrow
#

Why isn't this working?
embed.set_footer(text=self.config['embeds']['embed_footer_text'], icon_url=self.config['embeds']['embed_footer_image'])
The URL:
https://imgur.com/a/ds1Gdvs

naive briar
#

lmao

drifting arrow
#

Yeah I figured that out. The imgur link was a straight page not image

naive briar
#

That image is a little funny, not gonna lie

drifting arrow
#

:D

foggy spire
drifting arrow
foggy spire
drifting arrow
#

Never tried

#

Can I use "has_any_role" on a button?

tight mica
#

but you can add a check later for the roles

upbeat otter
unkempt canyonBOT
#

async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator) of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry).

You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members) to get this information.

Changed in version 2.0: Due to a breaking change in Discord’s API, this now returns a paginated iterator instead of a list.

Examples

Usage...
upbeat otter
#

You could try using this

foggy spire
#

done done.....

upbeat otter
#

nice

dusk shadow
#

🤔 uhhhhh... confusion...?

#

how would i fix that.
might be dum. :/
otherwise, idk why its doin that o_0

lyric solar
#

how do i embed this 😭 💀

dusk shadow
#

embed web images?
your link has "..png" at the end

dusk shadow
#

and... that works?

lyric solar
#

correct

dusk shadow
#

:?

lyric solar
#

look

#

idk how to embed this in an embed tho

#

so i thought this would work

hazy kraken
#

hi

lyric solar
#

hello

dusk shadow
#

i... im not sure that embeds can convert urls to images... they just dont do that.
youd need to add some sort of image section if its a url...
if its just the description of the embed, then it will just paste as plain text.

hazy kraken
#

i need some help

dusk shadow
#

i think the part is called... one sec

hazy kraken
#

idk why gaving me this error

lyric solar
hazy kraken
#
import discord
from discord.ext import commands
from discord.ui import Select, View

class HelpView(View):
    @discord.ui.select(
        placeholder='Click more for momo',
        options=[
            discord.SelectOption(
                label='home', 
                value='0', 
                description='momo Home Page'
            ),
            discord.SelectOption(
                label='anime', 
                value='1', 
                description='anime Page'
            )            
        ],
    ) 
    async def select_callback(self, select, interaction):
        select.disabled = True
        selected_value = interaction.data["values"][0]

        if selected_value == "0":
            thumbnail = self.bot.user.avatar_url
            embed = discord.Embed(
                title="**{} home page <3**".format(self.bot.user.name),  
                description="Descripción de la categoría 0")
            embed.set_thumbnail(url=thumbnail)
            embed.set_footer(text={}.format(self.bot.user.id), icon_url=self.bot.user.avatar_url) 
            await interaction.response.edit_message(embed=embed)
            
        if selected_value == "1":
            thumbnail = self.bot.user.avatar_url            
            embed = discord.Embed(
                title="**{} home page <3**".format(self.bot.user.name),  
                description="Descripción de la categoría 1")
            embed.set_thumbnail(url=self.bot.user.avatar_url)
            embed.set_footer(text={}.format(self.bot.user.id), icon_url=self.bot.user.avatar_url) 
            await interaction.response.edit_message(embed=embed)

class Help(commands.Cog):
    def __init__(self, bot):
        self.bot = bot 
        
    @commands.command(name="help")
    async def help(self, ctx):
        view = HelpView()
        embed = discord.Embed(
            title="**{} help page <3**".format(self.bot.user.name),
            description="**Categorías**\n\n0: Categoría 0\n\n1: Categoría 1",
            color=discord.Color.blue() 
        )
        await ctx.send("Selecciona una categoría:", view=view)

async def setup(bot): 
    await bot.add_cog(Help(bot)) 
dusk shadow
#

cover_image

hazy kraken
lyric solar
hazy kraken
#

oh?

lyric solar
#

this is how it should look like lol

#
class ExpandDropdownView(discord.ui.View):
    def __init__(self, data):
        super().__init__(timeout=None)
        self.add_item(ExpandDropdown(data))```
hazy kraken
#

maybe could explaining me.

lyric solar
#

found it wait

hazy kraken
#

oh alr

lyric solar
#

i don't think from discord.ui import Select, View does even do anything

#

and you mixed up Select with View

#

so switch View with Select

#

class ExpandDropdown(discord.ui.Select):
    def __init__(self, data):
        options = [
            discord.SelectOption(label=f"Expand #{i + 1}") for i in range(len(data))
        ]
        super().__init__(placeholder="Learn more...", options=options)
        self.data = data

    async def callback(self, interaction: discord.Interaction):
        with open('data.json', 'r', encoding='utf-8') as file:
            data = json.load(file)

        option_index = int(self.values[0].split('#')[-1]) - 1
        selected_data = data[option_index]
        frxd123 = "placeholder"
        embed = discord.Embed(
            title=f"{selected_data['title']}",
            description=f"{selected_data['title_expanded']}\n\n{selected_data['content']}",
            color=0xFFFFFF
        )
        embed.set_image(url=f'{selected_data['image_url']}')
        await interaction.response.send_message(embed=embed, ephemeral=True)

class ExpandDropdownView(discord.ui.View):
    def __init__(self, data):
        super().__init__(timeout=None)
        self.add_item(ExpandDropdown(data))

this is how mine looks like

dusk shadow
#

unless im not braining hard enough...

embed = discord.Embed()
embed.set_image(url="image_url")```
lyric solar
#

how do i move it up i dont like it down

dusk shadow
#

i think thats now discord embeds photos

#

unless you want the icon of the embed

lyric solar
#

sec

dusk shadow
#

the icon is SUPER small, so its ether deal with that, or have small

#

that be discord tho... :/

#

unless its

embed = discord.Embed()
embed.set_thumbnail(url="image_url")```
which is the smaller version
lyric solar
#

yea ik

#

but liek a friend of mine made the image up and not down

#

in d.js

#

idk if its possible in d.py

naive briar
#

Are you talking about thumbnails?

dusk shadow
#

yeaaa, no idea tbh.
to me, thats all ive dealt with, is the thumbnail and the main image

finite salmon
#

thumbnails 🔛🔝 and images at bottom

naive briar
unkempt canyonBOT
#

set_thumbnail(*, url)```
Sets the thumbnail for the embed content.

This function returns the class instance to allow for fluent-style chaining.

Changed in version 1.4: Passing `None` removes the thumbnail.
finite salmon
#

thats how discord works

dusk shadow
finite salmon
#

you cannot make images which are not thumbnails appear on top

dusk shadow
#

well, or make them bigger, they only i think are 64x64/128x128 in size

dusk shadow
finite salmon
dusk shadow
#

wa

#

what string... am i... ?

finite salmon
#

ova here

dusk shadow
#

OMFG

#

yep, thanks. me no brain today

#

🌫️ 🧠🌫️

finite salmon
#

lol

#

maybe you just need some rest

dusk shadow
#

nah more caffine

#

brain love caffeine

finite salmon
#

dam

#

ive never really felt caffeine work on me

#

sad

dusk shadow
#

GSupps

fallen fable
#

hey idk if any of you are familiar with node js but I got this error
SystemError [ERR_SYSTEM_ERROR]: A system error occurred: uv_os_get_passwd returned ENOENT (no such file or directory)
I thought it meant that postgres authentication was invalid or that the password wasn't correct in my env file but I double checked and it is no clue what to do from here
reposting from off topic to see if I can get some more specific advice

#

setting up a discord bot in a docker enviroment on a host

#

the documentation on said bot is pretty poor and made no mention of a postgres database needing to be used looking for any solutions or if at the very least this is an issue with the way the bot has been set up or with the way it was written

cold elbow
#

Hi

sick birch
fallen fable
sick birch
fallen fable
#

well im over

#

actually cuz I joined some while I had nitro

#

im over by 30 I guess ill have to clean some out

somber sky
#

i feel like i probably synced my commands and it changed the id's of the commands

slate swan
#

might be

#

i dont really know when the ids are regenerated

#

never checked it

somber sky
#

it probably is the sync because i just dont see the bot command id's reseting after the bot goes offline because then there would lowkey be like almost no point of having id's because the reason I use it is for the command mentioning or whatever and i think that it would be useless if the id's get reset after it goes offline

#

commands being synced just makes a lot more sense

#

cause its syncing every tree command

leaden olive
#

if i change bot to client, the command works again, but the command which shows me all of my coins wont work then

formal basin
#

How can I check if my discord bot stops running

#

???

#

like when the bot goes offline it will send a webhook to a certain channel

#

i know how to do the webhook part

#

just need to do the checking if the bot goes offline

lyric solar
#

also what type of unreliable host makes the vps go offline 😭

leaden olive
lyric solar
next oracle
#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.

next oracle
#

how do I make a discord bot

#

like deploy it

hushed galleon
flat pier
lyric solar
# flat pier what is rule 5 here
  1. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
#

how do i set a description of a slash command

flat pier
lyric solar
#

idk either

flat pier
lyric solar
#
@bot.event
async def on_ready():
    print("Bot is ready.")
    await bot.change_presence(activity=discord.Game(name="for real"))
    print("buddy")```

Why does it not buddy 😔
flat pier
#

how are you using slash commands then?

lyric solar
# flat pier how are you using slash commands then?
@bot.tree.command(name="refresh", description="Refresh the YEWS JSON File (in simple words, refresh the data.)")
async def refresh(ctx):
    """Refresh the YEWS JSON File (in simple words, refresh the data.)"""```
#

imma be honest idk which ones setting the desc

flat pier
#

bot.tree.command is an app_command

lyric solar
#

lies..

flat pier
#

no?

lyric solar
#

so i do bot.tree.command.describe()?

flat pier
#

no, you import app_commands from discord and use the decorator

lyric solar
#

😔

final iron
#

!d discord.app_commands.describe

unkempt canyonBOT
#

@discord.app_commands.describe(**parameters)```
Describes the given parameters by their name using the key of the keyword argument as the name.

Example:

```py
@app_commands.command(description='Bans a member')
@app_commands.describe(member='the member to ban')
async def ban(interaction: discord.Interaction, member: discord.Member):
    await interaction.response.send_message(f'Banned {member}')
```  Alternatively, you can describe parameters using Google, Sphinx, or Numpy style docstrings...
lyric solar
#

what im confused

final iron
#

even gives an example

lyric solar
#

so i did it right?

final iron
#

You're trying to set the description of a command, correct?

lyric solar
#

idk why the ... is there so im trying to set desc but its not working

lyric solar
final iron
#

Yeah

lyric solar
#

then yes

final iron
#

So there's a couple ways to do it

#

CommandTree.command has a description kwarg that sets it

#

Or, as mentioned before you can use a docstring

lyric solar
#

i forgot to sync

#

how do i interrupt this by a command:

async def setup_hook():
    asyncio.create_task(main())

bot.setup_hook = setup_hook```
flat pier
#

you're trying to interupt the setup_hook?

lyric solar
#

and start it up again on command

flat pier
#

to restart the entire bot?

lyric solar
#

it's complicated

#

im running two tasks

#

one is main
one is discord bot

#

its a really inefficient way to do it, i know

#

but idk how to do it any other way

flat pier
#

You can't (or well, shouldn't?) do that, you should just call bot.close()or have a script to run the bot again, or alternatively if you're trying to update commands, etc without shutting off the bot and you should be using Cogs

final iron
#

What does the main script do?

lyric solar
lyric solar
final iron
#

Yeah, but what does said script do

lyric solar
final iron
#

At certain intervals?

lyric solar
#

if there isnt any, pass, if there are updates, scrape the data of the updated site

final iron
#

Look into the tasks extension for that

lyric solar
#

no like i already have that working but like

#

i want to stop the main() task on command and start it up again

final iron
#

Will be significantly easier using the task extension

lyric solar
#

doc is like a wall of text and i cant read it

final iron
#

huh

lyric solar
#

i dont know how to read it

#

it melts my brain

flat pier
#

You can also call taskobject.stop from a command instead of trying to do whatever you're doing with another function

final iron
lyric solar
final iron
#

Yeah, go over it line by line

#

The first couple of code blocks are examples

lyric solar
final iron
#

The tasks extension is legitimately designed for exactly what you're doing

#

Using asyncio just over complicates it

lyric solar
#

or how to even use it infact, i need to get spoonfed

#

else i wont understand

final iron
#

Have you taken a look at the documentation?

flat pier
#

if you look at the docs it likely will spoonfeed you

lyric solar
#

idk where to look at

final iron
#

Documentation is essential for programming

lyric solar
flat pier
#

it immediately shows you a ton of examples before getting into it

lyric solar
#

i just don't like it

lyric solar
#

it doesnt even seem relevant

final iron
#

Why can't you use them?

flat pier
#

plently of them look very relevant seeing your code

lyric solar
#

i dont understand the api reference at all

#

i only understand the examples

final iron
#

Do you know what OOP is?

lyric solar
final iron
#

What specifically about the documentation do you not understand?

lyric solar
#

on how im supposed to implement it

final iron
#
@tasks.loop(seconds=...)
async def printing():
    # Do whatever

This is the simpliest implementation you'll get. You'll then want to call Loop.start() to start the loop

#

You'll probably want to call it in your setup_hook

lyric solar
#

i really don't wanna tamper with main, do i have to?

final iron
#

It's simplier than what you're doing right now

lyric solar
final iron
#

It's not though

lyric solar
#

i have some issues with it not fully scraping from the site

lyric solar
final iron
#

Why are you adverse to using tasks?

#

It's significantly easier to use

lyric solar
#

ill try using it but i literally dont know how to use it at all

final iron
#

You need to be specific with what you don't understand

lyric solar
#

so for now i change asyncio.create_task to loop.start(whatever)

lyric solar
final iron
lyric solar
#

@tasks.loop(seconds=...)

seconds = what the interval is to run the task is?

final iron
#

how am i supposed to implement it
I gave an example, and there's some examples in the documentation. Just try creating a very simple task and play around with it

final iron
unkempt canyonBOT
#

@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, name=None)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop).
lyric solar
#

that dont help

final iron
#

It's listed in the parameters section

lyric solar
#

what

final iron
#

dawg

lyric solar
#

😭

final iron
#

you gotta work with me here

#

Help is a 2 way street

lyric solar
#

can i remove my asyncio.sleep(60) if i have @tasks.loop(seconds=60)

final iron
#

I guess? I'll probably need more context to the full implementation of the code

lyric solar
#

so basically the tasks.loop will be put to the top of the code

#
@tasks.loop(seconds=60)
async def main():
    global previous_time, current_time, edition_url, data```
#

like this

#

i think im doing it right

#

and like if its already gonna loop every 60 seconds, i probably dont need asyncio.sleep(60) right?

final iron
#

No

naive briar
#

Oh no, that global ducky_concerned

lyric solar
lyric solar
flat pier
lyric solar
flat pier
#

ideally you shouldn't use globals like that

lyric solar
#

this should be fine now right?

final iron
#

you don't need the loop

lyric solar
flat pier
#

it can cause issues, especially with naming like current_time, previous_time and data

lyric solar
final iron
flat pier
#

alternatively you can use bot vars and naming that better describes the variables

lyric solar
#

its not supposed to be a one time request

#

its supposed to request the site every 60s

final iron
#

it won't though

lyric solar
#

???? wtf

#

why not

final iron
#

Do you know how a while loop works?

lyric solar
final iron
#

Okay, do me a favour

lyric solar
#

i thought tasks.loop(seconds=60) would be just like asyncio.sleep()

final iron
#

no

lyric solar
#

okay so i dont need that, noted.

flat pier
#

it creates a task with a function that exectues every 60 seconds

#

and to explain what a bot var is

bot = commands.Bot(...)
bot.my_descriptive_bot_variable = ...


# use it later
@tasks.loop(...)
async def my_task():
    print(bot.my_descriptive_bot_variable)
lyric solar
#

so that you can use bot.my_descriptive_bot_variable outside a function?

naive briar
#
# print "Meow" every 10 seconds. No need for while loops
@tasks.loop(seconds=10)
async def print_stuff():
    print("Meow")
#

🫠

final iron
#

I implore you to create a very simple task that prints something to see how they work

lyric solar
final iron
#

There's some misunderstanding of what a task actually is

naive briar
#

Yes?

lyric solar
#

but like its weird implementing it

final iron
#

Just try creating a very simple one to start with

#

I guarantee it's alot easier than you think

#

A task takes 3 lines to create and start (not including the code inside the task)

lyric solar
#

okay i made a task now how do i start it

final iron
#

You call Loop.start() on your function (the Loop object)

#

The docs show this as well fyi

lyric solar
#

no i dont get how to start it

final iron
#

dawg

lyric solar
#
@tasks.loop(seconds=3)
async def hi():
    print("hi")

got this far

final iron
#

look at the docs

lyric solar
#

the docs aint helping

naive briar
#

Why is that?

final iron
#

its shows you exactly how to start a task

flat pier
#

Also a note for when you do implement your functionality into a task, you should use @task.before_loop since you use discord api calls (which wont work at the point setup_hook is fired) and use bot.wait_until_ready

final iron
#

with an example

lyric solar
#

okay but where

final iron
#

self.printer.start()

lyric solar
#

😭 so i need to init it first

final iron
#

no

lyric solar
#

?

final iron
#

that's an example in a cog

#

Start the task in your setup_hook function

shrewd apex
#

or cog_load

lyric solar
#

i dont use cogs

final iron
#

i know

#

thats why im saying to do it in your setup_hook function

shrewd apex
#

^^

lyric solar
#
from discord.ext import tasks


@tasks.loop(seconds=3)
async def hi(self):
    print("hi")

async def setup_hook(self):
    self.hi.start()```
yea i dont think im ready for programming
#

i legit don't get it

#

either because its 4:37 am and im trying to code or its because im stupid

#

or both

final iron
#

That's onto basic python now

lyric solar
#

yes ik

#

but the examples are literally used in cogs

final iron
#

You don't need self if it's not in a class

lyric solar
final iron
#

yeah, they're not designed to be copied verbatim

final iron
lyric solar
#
@tasks.loop(seconds=3)
async def hi(self):
    print("hi")

async def setup_hook():
    hi.start()```
#

speaking of am i supposed to use ```py
from discord.ext import tasks

final iron
#

if a function is not inside a class it doesn't take self as an argument

lyric solar
lyric solar
final iron
#

you'll need to show your updated code first

lyric solar
#

oh oops i forgot to remove "self"

#
from discord.ext import tasks

@tasks.loop(seconds=3)
async def hi():
    print("hi")

async def setup_hook():
    hi.start()```
final iron
#

Okay, are you overwriting the default setup_hook method?

#

you had it earlier

lyric solar
final iron
#

this'll go into your file with your bot

lyric solar
#

i see

#
async def setup_hook():
    main.start()
#

did i do it right?

#

seems like it

final iron
#

does it work?

lyric solar
#

now did i fix the overcomplicating asyncio tasks?

final iron
#

maybe?

lyric solar
#

nvm its not supposed to do that 😭

#

its scraping the same time

#

whyyy 😔

#

yea its doing this

final iron
#

probably an issue with the code itself, not the task

lyric solar
final iron
#

print all the values and see what happens

lyric solar
final iron
#

All your time values you use I guess

lyric solar
#

yea its not dumping everytime

final iron
#

At the end of the day it's your code so you'll know it better than other people

lyric solar
vague matrix
#

Just out of curiosity, what is the purpose of your discord bot? @lyric solar

vague matrix
vague matrix
#

I would start using something like bs4 to parse the html

#

I don't think requests would do it ideally, maybe I'm wrong

shrewd apex
terse whale
#
import discord

# Discord bot token
TOKEN = 'bottoken'

# File path to search
FILE_PATH = 'cleanedfile.txt'

# Define intents
intents = discord.Intents.default()
intents.messages = True  # Enable message events

# Initialize the Discord client with intents
client = discord.Client(intents=intents)

@client.event
async def on_ready():
    print(f'{client.user} has connected to Discord!')

@client.event
async def on_message(message):
    # Check if the message is from a bot
    if message.author.bot:
        return

    # Copy the message content
    copied_message = message.content

    # Check if the copied message is not empty
    if copied_message.strip():  # strip() removes leading/trailing whitespaces
        # Read the file contents
        with open(FILE_PATH, 'r') as file:
            file_content = file.read()

        # Search for the message text in the file content
        if copied_message in file_content:
            response = 'Text found in the file!'
        else:
            response = 'Text not found in the file.'

        # Send the response back to the channel
        await message.channel.send(response)

# Run the bot
client.run(TOKEN)```  I need help, i am making a script that uses python and uses a discord bot token to read messages sent into a discord channel but it only gives me the username of the person who sent the message, it wont give me the content of the discord message. pls help ty.
golden portal
#

is this chatgpt code

#

anyways enable message_content intents

unkempt canyonBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

vapid parcel
#

Okay, so you know how you do a slash command n some will have a thing that says can not find what you are looking for? Like while you are typing something in? Like an auto complete feature? What is that? im not talking about options, im talking about where it will autofill it out..?

drifting arrow
#

what is the application id, what does it do/enable and do i need it?

vapid parcel
#

Found it.

faint rapids
leaden olive
hot sparrow
#

im trying to create something to "click" all unclicked buttons in a channel, how do i do that?

#

thinking of iterating through channel history but how do i get the View of a message?

#

nevermind i got it, but how do i "click" all the buttons of a view?

thick anvil
#

hey, how would you guys create a discord bot which listens to events outside of discord, so how do i not use discord to tell the bot to do something? i was thinking of using webhooks but that means i can not create slash commands

slate swan
hot sparrow
#

thats ok, i can just copy and paste the callback logic

reef basalt
#

How to join in teams and How to code with others in there anyone can help?

long pecan
#

Hey all,

Inside a command, can I just have the bot read/write a file or better not?

golden portal
long pecan
#

I want to create some form of history of an event. (I do not have the code yet to get this event)
But say I get the state of something every 30 minutes. I'd like to write to a file what the state was.
Then when calling a command, say !showhistory for example, I want to read the last 5? entries.

#

(im still very new to bots so I don't know how this will go with the whole async await story)

golden portal
#

if that's the case, file isn't a good way to store data especially in a concurrent function

#

just get a good database, maybe sqlite would be alright though

long pecan
#

okay, I'll have to learn about sqlite now too xD thanks!

lyric solar
#

is
while not bot.is_closed() even a thing

hot sparrow
#

is persistent listening to discord views broken? the buttons dont work unless its created during a bot's runtime. about 2 months ago, it was working even after bot runs are terminated and started again

class MyClient(discord.Client):
    def __init__(self, *, intents: discord.Intents):
        super().__init__(intents=intents)

    async def setup_hook(self):
        # Persistent listening
        self.add_view(PosNegView())
hushed galleon
pale zenith
lyric solar
#

and where i cant use cogs?

grand bobcat
#

weird thing, when i run my python script, it only prints out my file location, not the script itself, any fixes? On vs

dense topaz
#

Hii, can someone help me to decide which library choose for my discord bot? I used to use discord.py, and changed to pycord when it was discontinued, but quited discord few weeks after
I started to use discord again recently and just figured out that there're so many other libraries now 😭😭😭
Can someone make a pro/con list about each one? (discord.py, pycord, nextcord, hikari, disnake, etc)

sick birch
#

I'd also say the library has been around for the longest time so it's maintainers have more experience

hot sparrow
pale zenith
#

Late response lol, you replied at 2 AM

lyric solar
pale zenith
somber sky
#
@client.tree.command(description='Set Transactions Channel')
@app_commands.checks.has_permissions(manage_channels=True)
async def settransactionschannel(ctx, channel: discord.TextChannel):

    channel = channel.id

    async with aiosqlite.connect("main.db") as db:
        async with db.cursor() as cursor:
            await cursor.execute(
                'UPDATE users SET settransactionschannel= ? WHERE guild = ?', (
                    channel,
                    ctx.guild.id,
                ))
            tc = discord.Embed(
                title="Transactions Channel Set",
                description=f'Transactions channel has been set to <#{channel}>'
            )
            await ctx.response.send_message(embed=tc, ephemeral=True)
        await db.commit()```

how would i make a command where it sets a channel like this, but when you do the command it sends a dropdown menu to set the channel and then the dropdown menu lists all the server channels and which ever you pick is the one it sets
amber trellis
#

where and how do you guys host bots ?

slate swan
#

VPS

amber trellis
#

oo alright

robust fulcrum
tight mica
drifting arrow
drifting arrow
naive briar
#

Define a slash command, probably 🐈

drifting arrow
#

But..

from discord.app_commands import command
from discord.app_commands.checks import has_permissions
from discord import Interaction

@command(name="settransactionschannel", description='Set Transactions Channel')
@has_permissions(manage_channels=True)
async def settransactionschannel(ctx, interaction: Interaction, channel: discord.TextChannel):

    channel = channel.id

    async with aiosqlite.connect("main.db") as db:
        async with db.cursor() as cursor:
            await cursor.execute(
                'UPDATE users SET settransactionschannel= ? WHERE guild = ?', (
                    channel,
                    ctx.guild.id,
                ))
            tc = discord.Embed(
                title="Transactions Channel Set",
                description=f'Transactions channel has been set to <#{channel}>'
            )
            await ctx.response.send_message(embed=tc, ephemeral=True)
        await db.commit()
#

if it was a slash command that'd be proper

#

you probably dont need explicit imports. but i think it's neater

robust fulcrum
#

also they should use a global connection insetad of connecting again and again

drifting arrow
#

Changes:

  • Explicit imports, only importing what he needs.
  • Set the command name (Was missing)
  • Added the interaction that all slash commands have.
#

Also Im not a fan of this way:

            await cursor.execute(
                'UPDATE users SET settransactionschannel= ? WHERE guild = ?', (
                    channel,
                    ctx.guild.id,
                ))

I prefer:

query = "update users SET settransactionschannel = :channel_id WHERE guild = :guild_id"
params = {
"channel_id": channel.id,
"guild_id": interaction.guild.id
}
await cursor.execute(query, params)
#

He could also change this a bit:

from discord import Embed #Not needed but again, I like it.
embed = Embed(title="Transactions Channel Set",
              description=f'Transactions channel has been set to {channel.mention}'
            )
await interaction.response.send_message(embed=embed, ephemeral=True)
robust fulcrum
drifting arrow
#

I'm not an expert at SQL. but will the "UPDATE" insert if they're not in the database? or will it spit out an error?

amber trellis
#

no

#

i think it will punch out error better to go with insert when adding new values

drifting arrow
robust fulcrum
drifting arrow
robust fulcrum
drifting arrow
#

It's fine. it's just easier for less experienced people to understand

robust fulcrum
#

ye that fine for beginers

drifting arrow
#

I started on discordpy with no experience.

#

Making a discordbot was one of my first projects.

robust fulcrum
#

i also did same mistake

drifting arrow
#

:D

robust fulcrum
#

but i realized my mistake when i learnt python properly

drifting arrow
#

2 different people I guess.

#

He could also union for his channel

#

async def settransactionschannel(self, interaction: Interaction, channel: Union[TextChannel, Thread]):

#

if he wants to include threads/forums :D

naive briar
#

Also, I hate excessive explicit imports

#

You'd need to add another import every time you want to use something from the same module

#

But you do you, I guess

drifting arrow
#

You can probably just import the entire thing and call it a day

slate swan
sick panther
#

Hello,
I'm encountering the issue that the bot processes the on_message event after my command has been invoked. I can't find any possible issues within the logic or anything like that, I already tried multiple solutions and even tried to ask ChatGPT. I have a simple afk command which is structured like this:

    @commands.command()
    async def afk(self, ctx: commands.Context, *, reason: str = "AFK") -> None:
       
        # database code, saving the id, guild id, timestamp, reason and last pings. works perfectly

        return await ctx.send(f"You are now AFK. Reason: {reason}")

Now the issue here is the on_message event, which is for some reason, trigerring after the command has been invoked. Sometimes it doesn't, which confuses me a lot.

    @commands.Cog.listener()
    async def on_message(self, message: disnake.Message) -> None:
        if message.author == self.bot.user:
            return

        if message.guild:
            afk_user = await AfkCollection.find_one({"_id": message.author.id, "guild_id": message.guild.id})

            if afk_user:
                await AfkCollection.delete_one({"_id": afk_user["_id"]})
                welcome_back_message = random.choice([]) # List with messages
                await message.channel.send(welcome_back_message) 

# There's some more code, but that isn't relevant for this from what I can say.
golden portal
# sick panther Hello, I'm encountering the issue that the bot processes the on_message event af...

while i dont use disnake, i'm pretty sure the event invocation works the same, which is bot.on_message event is scheduled first before the listeners, when that happens your commands is processed earlier, the simplest way to avoid it is to use the @bot.event then trigger the process commands after you've processed this afk deletion logic so it entirely avoid the race condition, maybe something like ```py
@bot.event
async def on_message(message):
await bot.process_afk_things(message)
await bot.process_commands(message)

#

either that or a lock/delay when you first insert the afk data

#

i guess another way would be ```py
@commands.Cog.listener()
async def on_message(self, message):
ctx = await bot.get_context(message)
if ctx.valid and ctx.command.qualified_name == 'afk':
return
# afk logic

sick panther
golden portal
#

doing the second option is kinda extra function call but it's whatever

#

you're welcome

sick panther
#

Currently I only care about if it works, I can think further about it when I got more time. Main thing is I have it done now 😭

golden portal
#

oke

dusk shadow
#

i need a quick example of a bot adding a role and remove another one plz

#

i cant tell if its discord.member.add_role or something, cause it dont like it if i do that

#

also, is there a way to have a command ONLY show up to a specific role?
im using
@commands.has_any_role('roleone', 'roletwo') etc.
and it wont show up for me

golden portal
dusk shadow
#

slash

#

ive been converting all my prefix commands to slash recently, so thats why

long pecan
#

Alright firends,
DEBUG time:

| DEBUG | bot.utils.decorators | korty.codes tried to call the 'xyz' command and the command was used in an overridden context.
Whut?

dusk shadow
golden portal
# dusk shadow slash

you can't really hide it specifically from roles, but you can use discord.app_commands.default_permissions, this will hide slash according to their perms instead of roles

#

app_commands.checks.has_any_role do exist

long pecan
dusk shadow
long pecan
#

I just copy pasta'd the layout of an already existing function and changed it accordingly

#

But it's a good time to learn about decorators so maybe I should

dusk shadow
golden portal
#

yes that's a check

dusk shadow
#

ok, ill look into that, thanks!

long pecan
dusk shadow
naive briar
#

!d discord.Member.add_roles pithink

unkempt canyonBOT
#

await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)s.

You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles) to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)s must appear lower in the list of roles than the highest role of the member.
dusk shadow
#

OHHHH

#

the reason and atomic

#

do you need both in the line?

golden portal
#
role = discord.Object(role id)
await member.add_roles(role, reason="example")
dusk shadow
#

GOT it

#

ok, thanks yall

#

and its capital M... gayud daymun it

golden portal
dusk shadow
#

use brain, drink caffeine, loose sanity

golden portal
#

see the learning guide on the channel's topic

dusk shadow
#

@golden portal
sorry to keep buggin u,
i kinda decided to use the name instead of the ID of the role,...
so what i have is this

async def mute_user(ctx: discord.Interaction, user: str):
    discord_id = ctx.user.id
    if discord.utils.get(ctx.user.roles, name="Moderator♘"):
        await ctx.response.send_message("You do not have Privileges to use this command!", ephemeral=True)
        return
    role_to_remove = discord.utils.get(ctx.user.roles, name="Generic Role")
    if role_to_remove is not None:
        await discord.Member.remove_roles(role_to_remove, reason= "Muted User")
    new_role = discord.utils.get(ctx.user.roles, name="muted")
    if new_role is not None:
        await discord.Member.add_roles(new_role, reason="Muted User")
        await ctx.response.send_message("User was Sucessfully Un-Muted!", ephemeral=True)
    else:
        await ctx.response.send_message("Muted Role Not Found!", ephemeral=True)

i keep getting a Muted Role Not Found! error...

#

unless i worked this incorrectly, can it not find the name of the Moderator?

#

or i guess, does anyone know why its doing that :/

golden portal
#

are you trying to mute or unmute the user

dusk shadow
#

essentially Mute.
the function is to basically remove them entirely from most of the server when the new role is placed on the user

#

it removes the role that has chat permission and access to the entire server, and replaces it with a role that only gives the user a smaller place where others cant see their messages/ nor chat with other users and just mods/admins

golden portal
#

if that's the case the user wont have the muted role, you're trying to get the muted role from this user, hence None

dusk shadow
#

wai

#

did i flip it... somehow??? 🤦‍♀️

#

must be doing something wrong then.
i log in just fine.

#

beats me

dusk shadow
# golden portal if that's the case the user wont have the `muted` role, you're trying to get the...

ok. well...
im doing a horrible job at braining here

@client.tree.command(name="mute", description="Mutes a User. (Moderation Only)")
@app_commands.describe(user='User to Mute',)

async def mute_user(ctx: discord.Interaction, user: discord.Member.mention):
    role_to_remove = discord.utils.get(ctx.user.roles, name="Generic Role")
    if role_to_remove is not None:
        await discord.Member.mention.remove_roles(role_to_remove, reason= "Muted User")
    
    new_role = discord.utils.get(ctx.guild.roles, name="muted")
    if new_role is not None:
        await discord.Member.mention.add_roles(new_role, reason="Muted User")
        await ctx.response.send_message("User was Successfully Muted!", ephemeral=True)
    else:
        await ctx.response.send_message("Muted Role Not Found!", ephemeral=True)

i dont see exactly whats wrong here,
apparently theres an error with the first line on the @client.tree.command part.

#

i threw out the part where i require the mod perm to run it.
and just went to basics.

#

TypeError: unsupported type annotation <property object at 0x000002459BF32BB0>

golden portal
dusk shadow
#

but if i use discord.Member it does nothing

#

the intentional command is /mute @user

golden portal
#

doing discord.Member is the way to do it, i dont know what you mean by "does nothing"

dusk shadow
#

it dosent manage roles. at all.
it basically just says, yep, they have roles

#

no removal, nor adding roles

#

just, yep, they have em

golden portal
#

elaborate, because i dont understand

dusk shadow
#

well, when i did the command, it said, "User was Muted", but did nothing when it came to roles

#

and the bot has admin perms, so theres nothing wrong there
*the accout were trying to manage has no roles

#

discord.app_commands.errors.TransformerError: Failed to convert @member to Member
now after doing more tweaks, i get this

golden portal
#

okay, give me the current code, because i see multiple errors there

dusk shadow
#

hence, why i tried discord.Member.mention

golden portal
#

mention is a property, hence why it's erroring saying property is invalid

dusk shadow
#
@client.tree.command(name="mute", description="Mutes a User. (Moderation Only)")
@app_commands.describe(user='User to Mute',)

async def mute_user(ctx: discord.Interaction, user: discord.Member):
    role_to_remove = discord.utils.get(ctx.user.roles, name="Generic Role")
    if role_to_remove is not None:
        await discord.Member.remove_roles(role_to_remove, reason= "Muted User")
    
    new_role = discord.utils.get(ctx.guild.roles, name="muted")
    if new_role is not None:
        await discord.Member.add_roles(new_role, reason="Muted User")
        await ctx.response.send_message("User was Successfully Muted!", ephemeral=True)
    else:
        await ctx.response.send_message("Muted Role Not Found!", ephemeral=True)
golden portal
#

do you not get any errors from this?

golden portal
#

have you sync

dusk shadow
#

yea

golden portal
#

can't repro your error

dusk shadow
#

:/

#

ok, i ran it again, and it says it did it, but no roles were changed

#

bruv.

golden portal
#

okay, now, you're doing discord.Member.add_roles

#

that's wrong, use the instance of discord.Member

#

not the class

#

i.e user.add_roles(new_roles) since you named your Member object as user. like i've shown you earlier

dusk shadow
#

my novice coding really shows thru, huh.

#

thanks, now it works as intented

void mauve
#

Guys did someone worked with Discord API ?
Somehow every other request I am using works and returns correct response, but when I'm trying to get guild info at /guilds/{guild_id} it shows {"message": "401: Unauthorized", "code": 0}

Here is my api class

class DiscordAuth:
    client_id: int
    client_secret: str
    redirect_uri: str
    session: aiohttp.ClientSession | None

    def __init__(self, client_id: int, client_secret: str, redirect_uri: str):
        self.CLIENT_ID = client_id
        self.CLIENT_SECRET = client_secret
        self.REDIRECT_URI = redirect_uri

    async def setup(self):
        self.session = aiohttp.ClientSession()

    async def get_user(self, token):
        headers = {"Authorization": f"Bearer {token}"}

        async with self.session.get(API_ENDPOINT + "/users/@me", headers=headers) as response:
            return await response.json()

    async def get_current_guild(self, token, guild_id):
        headers = {"Authorization": f"Bearer {token}"}

        async with self.session.get(API_ENDPOINT + f"/guilds/{guild_id}", headers=headers) as response:
            return await response.json()

    async def get_user_guilds(self, token):
        headers = {"Authorization": f"Bearer {token}"}

        async with self.session.get(API_ENDPOINT + "/users/@me/guilds", headers=headers) as response:
            return await response.json()

    async def get_token_response(self, data):
        response = await self.session.post(API_ENDPOINT + "/oauth2/token", data=data)
        json_response = await response.json()

        access_token = json_response.get("access_token")
        refresh_token = json_response.get("refresh_token")
        expires_in = json_response.get("expires_in")

        if not access_token or not refresh_token:
            return None

        return access_token, refresh_token, expires_in
dusk shadow
#

ok. so theres ONE other weird issue im running into

async def mute_user(ctx: discord.Interaction, user: discord.Member):
    if discord.utils.get(ctx.user.roles, name="Moderator♘"):
        await ctx.response.send_message("You do not have Privileges to use this command!", ephemeral=True)
        return

so, i wanna make sure that if users have the moderator role, that they can use it and no one else.
right now, even if this is in the command, it still lets ANYONE use it.
if im not mistaken, i need a def for a check or what?

dusk shadow
void mauve
#

Bearer

#

And he has admin rights

dusk shadow
#

honestly duno.
i just know that when 401 comes up, its usually cause theres not access to a guild

somber sky
drifting arrow
#

Still a slash command

somber sky
#

ok but my questions wasnt about how to define a slash command. I already have 40+ commands and im not gonna re write them just for it to be "easier to read" when i already understand it

cold dew
#

i want to make my first slash command with @bot.slash_commands and it throws me this error

@bot.slash_command(guild_ids = 1205863180887269456, name = "test", description = "First slash command")
 ^^^^^^^^^^^^^^^^^

AttributeError: 'Bot' object has no attribute 'slash_command'. Did you mean: 'add_command'? (paste: https://paste.pythondiscord.com/EBIA)

cold dew
#

discord 2.3

#

python @slate swan

slate swan
#

(as the error suggests)

cold dew
#

i heard its implemented

severe sonnet
#

how do i implement tracemalloc in my discord.py bot?
i had done it outside my bot, but with my bot i have no idea
it's the only way i can track my tracebacks from my lark
lark don't show tracebacks unless from tracemalloc

slate swan
somber sky
#
@client.tree.command(description='Set Transactions Channel')
@app_commands.checks.has_permissions(manage_channels=True)
async def settransactionschannel(ctx, channel: discord.TextChannel):

    channel = channel.id

    async with aiosqlite.connect("main.db") as db:
        async with db.cursor() as cursor:
            await cursor.execute(
                'UPDATE users SET settransactionschannel= ? WHERE guild = ?', (
                    channel,
                    ctx.guild.id,
                ))
            tc = discord.Embed(
                title="Transactions Channel Set",
                description=f'Transactions channel has been set to <#{channel}>'
            )
            await ctx.response.send_message(embed=tc, ephemeral=True)
        await db.commit()```

how would i make a command where it sets a channel like this, but when you do the command it sends a dropdown menu to set the channel and then the dropdown menu lists all the server channels and which ever you pick is the one it sets
severe sonnet
#

dead chat XD

pale zenith
#

are you sure you didn't miss a more important part of the error, for example...
coroutine 'XXXXX' was never awaited

#

the solution, await it! simple as

severe sonnet
#

cus Lark don't give me any trace

#

without trace malloc

#

i don't get any traceback from Lark so it's hard to fix

#

due to that i need tracemalloc

pale zenith
#

🤨 that doesn't sound right

#

what's your code looking like?

severe sonnet
#

so i can't send it right now Leo

pale zenith
#

ok

#

I doubt tracemalloc is anything useful for your debugging endevours anywy.

severe sonnet
#

as you can see

severe sonnet
pale zenith
#

it sounds more like you're mistaken. tracemalloc is to trace memory blocks allocated by python

severe sonnet
#

unless there is a better error handler for Lark

pale zenith
#

I see. I stumbled upon your code in another server. let me see for myself

severe sonnet
#

sure

pale zenith
#

tracemalloc ain't something you need lol. not for this kind of debugging...

severe sonnet
#

but on my but it don't work

#

*bot

#

it just compiles in my gramma but stucks when go to transformer

severe sonnet
#

but still not working

#

like it stucks when it's about to execute the transformer thing it don't work

#

i used await

#

this is the output i get when i make a macro from discord

burnt coral
severe sonnet
#

sorry, my internet is not working

#

so i had to take screenshot

#

since my mobile internet is the only thing working rn

severe sonnet
# pale zenith .

hey leo, maybe if i send my my code to github for you to check would you check? So you have a better look to it?

severe sonnet
pale zenith
#

!remind new 7h this

unkempt canyonBOT
#
Naw.

Sorry, you can only do that in #bot-commands!

pale zenith
#

well that's fucking stupid

severe sonnet
dusk shadow
#

so.
imma need a quick pointer.

im trying to make my slash command only usable by a member with a specific role.
im seeing if user.guild.roles is working, but im not sure how i would phrase the argument.
anyone have pointers?

sick birch
#

this way people without the role won't even see it in the menu

upbeat otter
#

Can you do this using a bot though?

sick birch
#

I don't think that's offered through the API, no

upbeat otter
#

hmmm i see

drifting arrow
#

When you create a slash command you can set the paramater to "TextChannel"
And when you go to use that param on discord it shows you a list of every channel, is there a way to only show specific channels?
Like only channels you can type in or channels you can see?

naive briar
#

No

drifting arrow
#

:(

sick birch
#

indeed a :( moment

latent jay
#

Do footer embed fields support the <t:timestamp:R>

sick birch
slate swan
#

The format is predefined

shrewd apex
latent jay
#

But are timestamps allowed in the embed footer field?

shrewd apex
#

!d discord.Embed.timestamp

unkempt canyonBOT
#

The timestamp of the embed content. This is an aware datetime. If a naive datetime is passed, it is converted to an aware datetime with the local timezone.

shrewd apex
#

automatically set in the footer if u set this attribute

latent jay
#

oh sweet

smoky cedar
#

guys, i have

import logging

at the beginning of my code,
but this error keeps showing

reef mirage
#

Heya everyone pithink
I wanted to ask if it's possible to setup a bot in a server that when on a specific website they have connected discord account, when they receive a message on the website to alert the via bot DM if they are in the server to let em know there's a new message received?

upbeat otter
reef mirage
smoky cedar
dusk shadow
dusk shadow
#

yea, that doesnt work.

#

anyone can still use the command, thanks anyway :/

pale zenith
#

Discord already is a messaging app. thonk

amber trellis
#

my bot is not detecting any commands :/

#

altough it detects on_message type events

smoky cedar
#

guys is there a way to fix this error?

import discord
from discord import app_commands
from discord.ext import commands
import json, requests
from keep_alive import keep_alive

intents = discord.Intents.all()
bot = commands.Bot(command_prefix='c!', intents=intents)

@bot.event
async def on_ready():
  await bot.tree.sync()
  print(f"Logged In As {bot.user}")
  await bot.change_presence(
    activity=discord.Activity(
      type=discord.ActivityType.watching, 
  name=f'S: {len(bot.guilds)} | Fluxus Bypasser'))
       

@discord.app_commands.checks.cooldown(1, 2)
@bot.tree.command(name="bypass-fluxus", description="Get Fluxus Key")
async def fluxus(interaction, link: str):
    try:
        url = 'https://tiger-unbiased-quagga.ngrok-free.app/api/fluxus/v1/'
        data = {'link': link}
        headers = {'Content-Type': 'application/json'}
        r = requests.post(url, json=data, headers=headers)
        key = r.json()["info"]["key"]
      
        await     interaction.response.send_message(embed = discord.Embed(title="*** Bypass Fluxus Key rinx***",description = f"```Your Key : {(key)}```"))   
    except Exception as e:
      print(e)
      await interaction.response.send_message("Example: https://keysystem.fluxteam.net/android/checkpoint/start.php?HWID=xxxx", ephemeral=True)

@fluxus.error
async def on_test_error(interaction: discord.Interaction, error: app_commands.AppCommandError):
    if isinstance(error, app_commands.CommandOnCooldown):
        await interaction.response.send_message(str(error), ephemeral=True)

keep_alive()
bot.run("ok")
sick birch
amber trellis
#

ty for response though

pale zenith
severe sonnet
dusk shadow
#

trying to mess around with json files atm
i put together a function thats basically like a password manager.
i know its not the best thing to make, but im just making it to make it

@client.tree.command(name="save", description="Saves Credentials")
@app_commands.describe(account= "The account you are saving Credentials too.", username= "The username with the account.", password= "Password associated with account.")
async def save(interaction: discord.Interaction, account: str, username: str, password: str):
    if interaction is not None:
        save[account] = {
            "Username": username,
            "Password": password,
        }
        save_json(save)
        await interaction.response.send_message("Save Successful", ephemeral=True)
    else:
        await interaction.response.send_message("Failed to save credentials", ephemeral=True)

This is what i have so far, and at the moment, and i get an error around save[account]
anyone know why im getting an error?

dusk shadow
#
    save[account] = {
    ~~~~^^^^^^^^^
TypeError: 'Command' object does not support item assignment
sick birch
dusk shadow
#

meaning?

#

does it need to be a different name than the command?

sick birch
#

yes

near sail
#

your function's name is save and your dictionary is also the same

dusk shadow
#

ok, well that should be fixed now, but im getting another error apparently with my json file. :/
using a utilities.py as a loader for the json saving/loading functions.

  File "c:\Users\User\Desktop\pmanager\manager.py", line 27, in <module>
    write= write_cred_json()
           ^^^^^^^^^^^^^^^^^
  File "c:\Users\User\Desktop\pmanager\utilities.py", line 14, in write_cred_json
    returndata= json.load(file)
                ^^^^^^^^^^^^^^^
  File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\json\__init__.py", line 293, in load
    return loads(fp.read(),
                 ^^^^^^^^^
io.UnsupportedOperation: not readable

i have it set up almost exactly as my other bot to where it saves json data, so im taking most of the lines from there, so im not sure why im having this many issues :<

--- this is my utilities.py file ---

import json

def save_json(jsondata):
  with open("credentials.json", "w") as file:
    json.dump(jsondata, file, indent=4)

def read_cred_json():
   with open("credentials.json", "r") as file:
      returndata= json.load(file)
      return returndata
   
def write_cred_json():
   with open("credentials.json", "w") as file:
      returndata= json.load(file)
      return returndata
naive briar
#

But is trying to read it (json.load)

pale zenith
# severe sonnet macro.py

ok, that file seems fine. (I don't know lark so can't judge that, but you said it works standalone right?)

#

please provide your error logs

severe sonnet
#

but with bot don't

pale zenith
#

ok, what happens when you do that?

#

and in what file is the command definition?

severe sonnet
pale zenith
#

yes. tracebacks you may have

severe sonnet
#

there is a discord command called "macro create"

severe sonnet
#

cus lark only do tracebacks with tracemalloc

pale zenith
#

I am going to assume you're eating the errors

pale zenith
severe sonnet
pale zenith
#

do you have any error handlers? eating errors meaning that the error reaches the error handler, but you never log it

naive briar
#

Catching errors without doing anything with it (including not logging it)

pale zenith
#

github hasn't indexed your repo, so i can't search for myself

naive briar
#

I'm a noob 🐈

pale zenith
#

you're fine :patpat:

severe sonnet
#

as you can see it stops in printing the tokens and such from grammar

#

but then it shows no more erroers

#

thought i think i had set error handlers

#

and my vscode told me to disable pyright

#

it seems to gives me erroers

pale zenith
#

add the following to your bot.run:
bot.run(your stuff here, root_logger=True)

amber trellis
#

how do you guys host your bot

pale zenith
#

hetzner

#

good host pats

#

(free hosts don't exist)

amber trellis
#

you seem familiar have i seen you before -_-

pale zenith
#

mayhaps

amber trellis
#

ty for all help

pale zenith
#

yeah I mod there. lol no problem

severe sonnet
amber trellis
severe sonnet
#

as you can see

pale zenith
# amber trellis actually ? 💀

yeah how tf are hosts gonna pay the electricity bills, the internet bills, the employees that give maintenance to the servers, etc etc etc

#

nothing is free in this life. If it is then you're the product