#discord-bots

1 messages · Page 319 of 1

slate swan
#

!pastebin

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

final iron
#

Shouldn't be copying code

#

This is the problems it causes

#

You should understand what the code actually does and the concepts it uses before taking it

slate swan
final iron
final iron
#

Especially for beginners

slate swan
slate swan
# final iron Show your `blacklist` cog

this blacklist.py code

`import discord
from discord.ui import View, button
import json
import requests

rednerLink = 'https://oauth-azureless.onrender.com' # your OAuth render link

class BlacklistView(View):
def init(self) -> None:
super().init(timeout=None)

@button(label="Blacklist", style=discord.ButtonStyle.red, custom_id="blacklist")
async def closeTicket(self, interaction: discord.Interaction):
    await interaction.response.defer(ephemeral=True)

    password = "MaterWelonFr336"
    url = f"{rednerLink}/deleteKey?password={password}&key={interaction.user.id}"

    response = requests.get(url)
    embed = discord.Embed(
        title="OAuth Key Deletion",
        description=response.text,
        color=discord.Color.red()
    )

    await interaction.followup.send(embed=embed, ephemeral=True)

`

final iron
#

Where's your commands.Cog subclass

final iron
slate swan
final iron
#

Okay, so you're trying to load a cog named blacklist, but it doesn't exist...

final iron
#

So, stop trying to load it lol

slate swan
final iron
#

Don't pass it as a cog when you load your extensions...

slate swan
# final iron Don't pass it as a cog when you load your extensions...

`C:\Users\abhay\OneDrive\Desktop\mater bot>python main.py
[2023-11-04 09:33:22] [INFO ] discord.client: logging in using static token
Traceback (most recent call last):
File "C:\Users\abhay\OneDrive\Desktop\mater bot\main.py", line 25, in <module>
client.run("grrtoken") # bot token inside quotes
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\abhay\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 860, in run
asyncio.run(runner())
File "C:\Users\abhay\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\abhay\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\abhay\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\abhay\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 849, in runner
await self.start(token, reconnect=reconnect)
File "C:\Users\abhay\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 777, in start
await self.login(token)
File "C:\Users\abhay\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 621, in login
await self.setup_hook()
File "C:\Users\abhay\OneDrive\Desktop\mater bot\main.py", line 14, in setup_hook
for ext in self.cogslist:
^^^^^^^^^^^^^
AttributeError: 'Client' object has no attribute 'cogslist'

C:\Users\abhay\OneDrive\Desktop\mater bot>`

final iron
#

Same error as before...

#

I'm not going to entertain this

slate swan
#

bruh

final iron
#

It's literally the same error as before

slate swan
#

:/

final iron
#

It was

#

Then you changed something

#

And we're back a step

slate swan
#

ok i reversed the code here it error

#

discord.ext.commands.errors.ExtensionNotFound: Extension 'cogs.blacklist' could not be loaded.

final iron
final iron
#

I already told you how to do that as well

#

We are unfortunately going around in a circle

#

These are some prerequisites discord.py. It's not positioned as a beginner library so it does use quite a few intermediate concepts

- Primitive data types
- Operators
- Data structures
- Importing
- Variables, namespace and scope
- String formatting
- OOP
- Control flow
- Exception handling
- Function definitions
- Classes, objects, attributes and methods
- Console usage, interpreters and environments
- Decorators

Useful to know:
- Asyncio basics
- What is blocking?
- Logging
- knowing how to read docs properly
#

!resources

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

slate swan
#

@final iron ty got fixed

final iron
#

Great

slate swan
#

C:\Users\abhay\OneDrive\Desktop\mater bot>python main.py [2023-11-04 09:37:48] [INFO ] discord.client: logging in using static token [2023-11-04 09:37:50] [INFO ] discord.gateway: Shard ID None has connected to Gateway (Session ID: 68d7ffade663ff75635074b6159bbb07). ←[40m←[32m04:07:S UTC←[49m←[37m←[1m Logged in as ←[33mBotX-Oauth ←[40m←[32m04:07:S UTC←[49m←[37m←[1m Bot ID ←[33m1168792749844201483 ←[40m←[32m04:07:S UTC←[49m←[37m←[1m Discord Version ←[33m2.3.2 ←[40m←[32m04:07:S UTC←[49m←[37m←[1m Python Version ←[33m3.11.6

slate swan
final iron
#

Just saying, you're going to run into a brick wall again until somebody helps you

final iron
#

Setting aside a month to learn those concepts will benefit you in the future, as right now you need somebody to hold your hand and guide you with every single error

snow coral
#

!paste

#

basically when the command is run, it isn't "reading" the players responses, isnt reacting at all, aswell as adding players to the winners/eliminated variable & im just a bit confused on why.

https://paste.pythondiscord.com/FKFA

#

line 47 btw

honest falcon
#

i tried to code a discord chess bot, but whenever i test it, it only register the white move, even when the bot said it black turn, can anyone help me
here the code:

import discord
from discord.ext import commands
import chess
import chess.svg
from cairosvg import svg2png

intents = discord.Intents.default()
bot = commands.Bot(command_prefix='.', intents=intents)

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name}')

@bot.command()
async def new(ctx):
    chess.Board()
    game = chess.Board()
    await ctx.send("Chess game started!")
    if game.turn:
        await ctx.send("White's turn")
    else:
        await ctx.send("Black's turn")
    await ctx.send(file=discord.File("board1.png"))

@bot.command()
async def move(ctx, move):
    game = chess.Board()
    print(game.legal_moves)
    if game.legal_moves:
        game.push_san(move)
    else:
        await ctx.send("Invalid move. Please try again.")

    with open("board.svg", "w") as f:
       f.write(chess.svg.board(board=game))

    svg2png(url="board.svg", write_to="board.png")

    await ctx.send(file=discord.File("board.png"))
    if game.turn:
        await ctx.send("White's turn")
    else:
        await ctx.send("Black's turn")

    if game.is_checkmate():
        await ctx.send("Checkmate! Game over.")
    elif game.is_check():
        await ctx.send("Check!")
    elif game.is_stalemate():
        await ctx.send("Stalemate! Game over.")


bot.run('token')
oak abyss
#

anyone would like to work with me on a discord python bot for roblox?

vale wing
#

Nah

vale wing
vale wing
#

You have bad condition here too

if game.turn```
#

It will always be true

#

You should check

if game.turn == chess.WHITE```
honest falcon
#

Ah i already fixed it, ty anyway

slate swan
#

Line 266

#

Error says all

#

You're using spaces and tabs for indentation instead of just spaces or just tabs

#

yeah and?

#

Either just use spaces or tabs????

#

only in that line?

#

or the whole code

fading yew
#

i need txt to gif

#

but can't move ?

#

the long like that

cyan eagle
slate swan
#

How do I get started learning discord bots any resources?

glacial topaz
#

can i use pycharm to code a discord bot

glacial topaz
vale wing
#

You can use pycharm for any python project (sometimes not even python)

vale wing
slate swan
vale wing
#

Dpy was resumed long time ago

#

Since this spring for sure

#

However disnake is still better than it ☺️

slate swan
#

Any resources on disnake

#

I mean I couldn't find a good tutorial or course up to date using /commands

glacial topaz
#

guys i got a question

#

so theres this online IDE called replit

#

and if i make a bot on there im afraid that somone is gonna do somthing malicous with my discord bot because its public. Is that valid? or in order for somone to access my bot they need the token right?

vale wing
#

Use pycharm, if you have issues I can help

glacial topaz
#

alright

vale wing
#

People can barely do anything malicious with your code (unless you have serious vulnerabilities, they can get exploited even without knowing code, publicity just makes that faster), open source projects exist with no issues and there are tools for privately storing tokens, replit is just bad

glacial topaz
#

ah i see

#

thats good to know

glacial topaz
vale wing
glacial topaz
#

oh as in how it doesnt complete "

#

""

vale wing
#

You tried pycharm?

glacial topaz
#

yes

#

i like it

vale wing
#

Notice how when you type something it suggests variants

glacial topaz
#

yeah

final iron
# glacial topaz what about replit is bad. i havent used it before so idk
  • The machines are super underpowered.

    • This means your bot will lag a lot as it gets bigger.
  • You need to run a webserver alongside your bot to prevent it from being shut off.

    • This isn't a trivial task, and eats more of the machines power.
  • Repl.it uses an ephemeral file system.

    • This means any file you saved via your bot will be overwritten when you next launch.
  • They use a shared IP for everything running on the service.
    This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you

slate swan
#

@shrewd apex

shrewd apex
#

sup

shrewd apex
slate swan
shrewd apex
#

sure

cyan eagle
#

Wahts this

robust fulcrum
#

I recommend you just code in your local environment

slate swan
cyan eagle
#

I have to host 30 different bots

#

And i dont have pc/laptops

cyan eagle
naive briar
cyan eagle
#

Yes

#

For future planning Esp_Luv

cyan eagle
naive briar
#

No, and there isn't any

#

If there is, it will not be reliable or safe

#

If there's one that is reliable or safe, it would not last forever

final iron
sick birch
#

EKS/GKE/AKS however are all expensive, DOKS much less so and is my personal favorite

vale wing
#

@slate swan new acc? Lmk in bobux server cause we will need to mess up with constants again if so skull_c

vale wing
final iron
#

24/7 hosting of 30 bots for free is insane lmao

final iron
slate swan
shrewd fjord
#

Ok it worked again smh

brazen geyser
#

hey guys, can someone help make commands group please?

warm canopy
#

I need help with my discord bot code

shrewd fjord
unkempt canyonBOT
#

@group(*args, **kwargs)```
A shortcut decorator that invokes [`group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.group) and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command).
brazen geyser
meager rock
#

no

hybrid light
#

hello, how to pin this response? message.pin() is not working

fading marlin
#

You have to retrieve the message via Interaction.original_response and then pin it

#

InteractionResponse.send_message does not return anything

brazen geyser
meager rock
#

i think using command options instead of a subcommand would be better option
/reload [option:cog] where cog can be an optional argument

onyx elk
#

can someone help add a menu to choose the times?

@client.tree.command()
async def ban(interaction: discord.Interaction, user: discord.User, delete_option: Optional[str] = "None"):
    """Ban a user from the server and optionally delete previous messages."""

    delete_options = [
        discord.SelectOption(label="Don't Delete", value="None"),
        discord.SelectOption(label="Previous 1 Hour", value="previous 1 hour"),
        discord.SelectOption(label="Previous 6 Hours", value="previous 6 hours"),
        discord.SelectOption(label="Previous 12 Hours", value="previous 12 hours"),
        discord.SelectOption(label="Previous 24 Hours", value="previous 24 hours"),
        discord.SelectOption(label="Previous 3 Days", value="previous 3 days"),
        discord.SelectOption(label="Previous 7 Days", value="previous 7 days"),
    ]

    select_menu = discord.SelectMenu(
        custom_id="delete_option",
        options=delete_options,
        placeholder="Select a delete option"
    )
  
    action_row = discord.ActionRow(select_menu)

    if interaction.user.guild_permissions.ban_members or interaction.user.guild_permissions.administrator:
        try:
            await user.ban()
          
            delete_timeframes = {
                "None": None,
                "previous 1 hour": datetime.timedelta(hours=1),
                "previous 6 hours": datetime.timedelta(hours=6),
                "previous 12 hours": datetime.timedelta(hours=12),
                "previous 24 hours": datetime.timedelta(hours=24),
                "previous 3 days": datetime.timedelta(days=3),
                "previous 7 days": datetime.timedelta(days=7),
            }
            delete_duration = delete_timeframes.get(delete_option, None)

            if delete_duration:
                embed = discord.Embed(
                    title="✅ Ban Successful",
                    description=f"{user.mention} has been banned from the server, and previous messages within the specified timeframe have been deleted.",
                    color=discord.Color.green()
                )
            else:
                embed = discord.Embed(
                    title="✅ Ban Successful",
                    description=f"{user.mention} has been banned from the server. No previous messages were deleted.",
                    color=discord.Color.green()
                )

            await interaction.response.send_message(embed=embed, components=[action_row])
        except discord.Forbidden:
            embed = discord.Embed(
                title="❌ Missing Permissions",
                description="I don't have permission to ban users or delete messages.",
                color=discord.Color.red()
            )
            await interaction.response.send_message(embed=embed)
    else:
        embed = discord.Embed(
            title="❌ Missing Permissions",
            description="You don't have permission to use this command.",
            color=discord.Color.red()
        )
        await interaction.response.send_message(embed=embed)```
#

if you wanna help can you ping me as i might be doing some coding

slate swan
#

!d discord.app_commands.choices

unkempt canyonBOT
#

@discord.app_commands.choices(**parameters)```
Instructs the given parameters by their name to use the given choices for their choices.

Example...
onyx elk
# slate swan !d discord.app_commands.choices
@client.tree.command()
@app_commands.choices(delete_option=[
    Choice(name="Don't Delete", value="None"),
    Choice(name="Previous 1 Hour", value="previous 1 hour"),
    Choice(name="Previous 6 Hours", value="previous 6 hours"),
    Choice(name="Previous 12 Hours", value="previous 12 hours"),
    Choice(name="Previous 24 Hours", value="previous 24 hours"),
    Choice(name="Previous 3 Days", value="previous 3 days"),
    Choice(name="Previous 7 Days", value="previous 7 days"),
])
async def ban(interaction: discord.Interaction, user: discord.User, delete_option: Choice[str] = Choice(name="Don't Delete", value="None")):
    """Ban a user from the server and optionally delete previous messages."""
    
    select_menu = discord.SelectMenu(
        custom_id="delete_option",
        options=app_commands.selects.delete_option, 
        placeholder="Select a delete option"
    )

    action_row = discord.ActionRow(select_menu)

    if interaction.user.guild_permissions.ban_members or interaction.user.guild_permissions.administrator:
        try:
            await user.ban()
            delete_timeframes = {
                "None": None,
                "previous 1 hour": datetime.timedelta(hours=1),
                "previous 6 hours": datetime.timedelta(hours=6),
                "previous 12 hours": datetime.timedelta(hours=12),
                "previous 24 hours": datetime.timedelta(hours=24),
                "previous 3 days": datetime.timedelta(days=3),
                "previous 7 days": datetime.timedelta(days=7),
            }
            delete_duration = delete_timeframes.get(delete_option, None)

            if delete_duration:
                embed = discord.Embed(
                    title="✅ Ban Successful",
                    description=f"{user.mention} has been banned from the server, and previous messages within the specified timeframe have been deleted.",
                    color=discord.Color.green()
                )
            else:
                embed = discord.Embed(
                    title="✅ Ban Successful",
                    description=f"{user.mention} has been banned from the server. No previous messages were deleted.",
                    color=discord.Color.green()
                )

            await interaction.response.send_message(embed=embed, components=[action_row])
        except discord.Forbidden:
            embed = discord.Embed(
                title="❌ Missing Permissions",
                description="I don't have permission to ban users or delete messages.",
                color=discord.Color.red()
            )
            await interaction.response.send_message(embed=embed)
    else:
        embed = discord.Embed(
            title="❌ Missing Permissions",
            description="You don't have permission to use this command.",
            color=discord.Color.red()
        )
        await interaction.response.send_message(embed=embed)```
#

for some odd reason i feel different

#

@slate swan Choice isnt defined

brazen geyser
onyx elk
brazen geyser
#

ive never used select menus

onyx elk
#

bruhh

final iron
slate swan
#

!d discord.app_commands.Choice

unkempt canyonBOT
#

class discord.app_commands.Choice(*, name, value)```
Represents an application command argument choice.

New in version 2.0.

x == y Checks if two choices are equal.

x != y Checks if two choices are not equal.

hash(x) Returns the choice’s hash.
slate swan
#

Basic python

final iron
#

And this is why we don’t blindly copy code we find online

slate swan
#

Or at least copy with the imports lulw

final iron
#

What’s the point of making a ban command anyway

#

Discord already has one built in

#

Creating a ban command is objectively worse than discords as you cannot search the audit logs for who did it

#

Harder to keep track of etc

onyx elk
brazen geyser
final iron
brazen geyser
#

or maybe you can do it even with builded one, im not that good, im beginner too

brazen geyser
final iron
#

If you want. That’s completely useless though as sending messages to a channel is not a good way to log bans

brazen geyser
#

ohh, okay, thank you for telling me! Wingman_Love

#

like I said, Im beginner too, so I dont want to say something thats not even true.

mighty lynx
#

Hey, I have my bots nested so that they each have a function that prints a message in the terminal when they start, and also in that function is a command to start another bot. I'm sure there is a better way to do this, but this is what I came up with. For some reason only the first bot is starting and it's not moving on to the next one. It was working fine, but since I have added another bot it's been having problems. I don't know if it's a memory problem or what.

fading marlin
#

Code? and why do you have multiple bots?

mighty lynx
#

With a single command in a separate file in the folder.

#

It's separate files for every bot.

final iron
#

Show the code on how you’re running the files

mighty lynx
#

Okay, how do I show code blocks?

fading marlin
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

mighty lynx
#

I don't know if I did it right.

final iron
#

So all that can be interpreted from that code is you’re running something with run_until_complete

mighty lynx
#

I'm new to making these, so I know there are probably better ways of doing things.

final iron
#

In the code you showed you're only running 1 bot

mighty lynx
#

Really? The second link I posted?

fading marlin
#

There are some blocking stuff in your code

#

What's your entrypoint?

mighty lynx
#

What's an entrypoint? The first file?

fading marlin
#

Yeah, the script you run to start off the whole thing

mighty lynx
#

Yeah, that's the first file.

fading marlin
#

Alright, and I'm guessing you're expecting GEBot -> pollbot -> ytsearchbot to start off afterwards?

final iron
mighty lynx
#

Yeah. It's supposed to start the ds3command, then ds3command is supposed to start the next one.

fading marlin
#

Also, is there any particular reason why you have 4 bots instead of just 1?

mighty lynx
#

I was meaning for them to be used by different people for different things on different servers. The uses I had in mind seemed too different for just one bot.

fading marlin
#

Why not use cogs and a module that toggles commands depending on the server?

mighty lynx
#

I don't know what cogs are.

final iron
mighty lynx
#

The bots are supposed to be for specific people, so I didn't want them to be the same bot.

robust fulcrum
shrewd fjord
clear lark
naive briar
#

You can't, it's only for modals

turbid condor
#

guys any idea how to add a cooldown to select menu?

shrewd fjord
turbid condor
solid skiff
#
async def SendStandings():
    now = datetime.datetime.now
    #then = now+dt.timedelta(days=1)
    then = datetime.datetime.now.replace(hours=6, minutes=53)
    waitTime = (then - now).total_seconds()
    await asyncio.sleep(waitTime)```
#

trying to make a message than sends at set time each day

#

'builtin_function_or_method' object has no attribute 'replace'

naive briar
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | <built-in method now of type object at 0x7f00d9ce9ae0>
002 | 2023-11-05 07:25:47.114448
cyan eagle
fiery girder
#

just buy a grass mouse pad

#

problem fixed

#

or just a grass pad and put it on your arm rest or something

solid skiff
#
embed_var = discord.Embed(title=f"League Standings", description=f"{date.today().strftime('%B %d, %Y')}", color=0x2d5796)
        embed_var.add_field(name="", value=f"\n{output}\n
", inline=False)
        embed_var.set_image(url="https://www.howtogeek.com/wpcontent/uploads/2021/01/windows_hello_hero_2.jpg?width=1198&trim=1,1&bg-color=000&pad=1,1")
        message_channel = bot.get_channel(1169634999637659711)
        await message_channel.send(embed=embed_var)```
#

no image?

#

haha help

brazen geyser
cyan eagle
#

How to fix

cyan eagle
cyan eagle
cyan eagle
shrewd fjord
#

Read the error

#

!e
commands

unkempt canyonBOT
#

@shrewd fjord :x: Your 3.12 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     commands
004 | NameError: name 'commands' is not defined
shrewd fjord
cyan eagle
solid skiff
shrewd fjord
shrewd fjord
cyan eagle
solid skiff
solid skiff
shrewd fjord
#

You can solve it by this steps,

  • request to the image url
  • get the bytes of the returned image
  • and then use bytesio to send it
cyan eagle
#

Idk how to define command

solid skiff
#

😂

cyan eagle
solid skiff
shrewd fjord
#

!resources

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

cyan eagle
solid skiff
#

if you dont know how to import libraries

shrewd fjord
#

Please complete these before making a discord bot

solid skiff
#

stop trying to make bots

#

and learn python

cyan eagle
#

Comeon guys

cyan eagle
#

Please

solid skiff
cyan eagle
#

Tell

#

4s of slowmode uff

solid skiff
#

ill give you a clue

shrewd fjord
#

from discord.ext import commands dead

shrewd fjord
#

Yeah fr

solid skiff
#

hahah

shrewd fjord
#

Idh patience xd

solid skiff
#

haha

solid skiff
shrewd fjord
solid skiff
#

or its gonna take ages to make a bot

shrewd fjord
#

Unless you ctrl c and v ☠️

solid skiff
#

That's what ive done for half of my bot tbf ngl

#

I don't actually know python

#

🤫

shrewd fjord
solid skiff
#

that someone begged to make a bot

shrewd fjord
#

Make your own python :) ok let's not talk about these stuff now off topic xd

void mauve
#

Guys, I have a question, Is it possible to make ephemeral message that is visible for certain role instead of the interaction?

shrewd fjord
#

No

final iron
fiery girder
#

what is the easiet way to handle on_command_error(ctx, error)

golden portal
#

wdym 'easiest'? just handle it

fiery girder
#

i mean like how should i handle them

#

should i just leave it be or should i just resend the error

slate swan
#

you should check what error it is

fiery girder
slate swan
#

then when its something like MissingRequiredArgument notify user

#

if none of your error checks fires reraise the error

fiery girder
golden portal
#

either reraise or send it to yourself through like sentry and etc for better handling

fiery girder
#

oh thanks

golden portal
fiery girder
#

all done

#

how do i make a command specificly for my guild

forest topaz
random kiln
#
        len_cmd = 0
        for cmd in self.bot.walk_commands():
            len_cmd += 1``` Excuse me sir, how can I check whether a user can use commands or not? in looping walk_command
formal basin
#
@bot.event
async def on_interaction(interaction: discord.Interaction):  
   if interaction.channel.is_nsfw():
       embed = discord.Embed(title="An Error has occured", description="zagzag does not support NSFW channels", colour=discord.Colour.red())
       button = Button(label="support server", url="")
       view = View()
       view.add_item(button)
       await interaction.followup.send(content="zagzag does not support NSFW channels", embed=embed, view=view)
       return
       
   elif r.exists(interaction.user.id):
       embed = discord.Embed(title="An Error has occured", description=f"You are banned from using zagzag", colour=discord.Colour.red())
       button = Button(label="support server", url="")
       view = View()
       view.add_item(button)
       await interaction.followup.send(content="You are banned from using zagzag", embed=embed, view=view)
       return
``` When this is executed it works but the command still executes
formal basin
#

Anyone know?

final iron
#

You can create a custom/global check

formal basin
final iron
#

I literally just said it

formal basin
final iron
#

If you want

formal basin
final iron
#

I also offered an alternate solution

formal basin
#

where?

final iron
#

In the exact same line

formal basin
#

a global check?

#

whats that?

final iron
#

A check that applies to all of your slash commands

formal basin
final iron
#

You need to create a subclass of CommandTree, and then override the interaction_check method. You can then do your processing in there. Return True if it’s allowed, return False if it isn’t

#

!d discord.app_commands.CommandTree

unkempt canyonBOT
#

class discord.app_commands.CommandTree(client, *, fallback_to_global=True)```
Represents a container that holds application command information.
final iron
#

!d discord.app_commands.CommandTree.interaction_check

unkempt canyonBOT
#

await interaction_check(interaction, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

A global check to determine if an [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) should be processed by the tree.

The default implementation returns True (all interactions are processed), but can be overridden if custom behaviour is desired.
formal basin
final iron
#

No

#

What

formal basin
final iron
#

You don’t need an init

formal basin
#

class Treecommand(discord.app_commands.CommandTree): so just this

final iron
#

There’s more obviously

#

But that’s correct so far

formal basin
final iron
#

I already said it above

formal basin
final iron
#

That is interaction_check and what I linked, yes

formal basin
final iron
#

Use what

formal basin
final iron
#

I already explained that above as well

formal basin
final iron
#

You don’t know how to return a value?

formal basin
#

i do

#

but using interaction_check

#

or do i do return interaction_check

final iron
#

No

#

You return True/False, as I already explained above

formal basin
#

so return False to stop it

final iron
#

Yes

formal basin
#

like that?

final iron
#

No…

#

As I already explained above, you need to override the interaction_check method

formal basin
#

how do I override it?

#

await interaction_check(interaction, return False)

final iron
#

You define a method called interaction_check

#

Then do all your processing there

formal basin
final iron
#

You don’t know how to define a function…?

formal basin
final iron
#

!resources

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

formal basin
#

ohh

#

wait

#

just a normal function?

final iron
#

Discord.py isn’t a beginner library. There’s no point in doing this if people have to hold your hand through this

formal basin
#

no do you mean a normal func?

#

ohhh

#

i think i get it

final iron
unkempt canyonBOT
#

await can_run(ctx, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Checks if the command can be executed by checking all the predicates inside the [`checks`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command.checks) attribute. This also checks whether the command is disabled.

Changed in version 1.3: Checks whether the command is disabled or not

Changed in version 2.0: `ctx` parameter is now positional-only.
final iron
#

Groups also have a can_run method

formal basin
#
async def interaction_check(inter):
 if inter.channel.is_nsfw():
       embed = discord.Embed(title="An Error has occured", description="zagzag does not support NSFW channels", colour=discord.Colour.red())
       button = Button(label="support server", url="")
       view = View()
       view.add_item(button)
       await inter.followup.send(content="zagzag does not support NSFW channels", embed=embed, view=view)
       return False


#an event

await interaction_check(interaction, /)```
cold sonnet
#

but you don't know whether it's because of the invoker

#

innit

#

if you have multiple checks

#

yeah it doesn't even matter nvm

formal basin
#
async def interaction_check(inter):
 if not inter.channel.is_nsfw():
       return True
 else:
       embed = discord.Embed(title="An Error has occured", description="zagzag does not support NSFW channels", colour=discord.Colour.red())
       button = Button(label="support server", url="")
       view = View()
       view.add_item(button)
       await inter.followup.send(content="zagzag does not support NSFW channels", embed=embed, view=view)
 
 if not r.exists(inter.user.id):
       return True
 else:
      embed = discord.Embed(title="An Error has occured", description=f"You are banned from using zagzag", colour=discord.Colour.red())
      button = Button(label="support server", url="")
      view = View()
      view.add_item(button)
      await inter.followup.send(content="You are banned from using zagzag", embed=embed, view=view)
   ```  How can I get it to return false
#
async def interaction_check(inter):
 if inter.channel.is_nsfw():
       embed = discord.Embed(title="An Error has occured", description="zagzag does not support NSFW channels", colour=discord.Colour.red())
       button = Button(label="support server", url="")
       view = View()
       view.add_item(button)
       await inter.followup.send(content="zagzag does not support NSFW channels", embed=embed, view=view)
       return False
 elif r.exists(inter.user.id):
      embed = discord.Embed(title="An Error has occured", description=f"You are banned from using zagzag", colour=discord.Colour.red())
      button = Button(label="support server", url="")
      view = View()
      view.add_item(button)
      await inter.followup.send(content="You are banned from using zagzag", embed=embed, view=view)
      return False
 
 
   


@bot.event
async def on_interaction(inter: discord.Interaction): 
  await interaction_check(inter)

The command is still executing

final iron
formal basin
slate swan
#

Ask this question to yourself:

If it's not working, is it right?

formal basin
slate swan
#

The command is still executing

That's definitely not working

formal basin
#
async def interaction_check(inter):
 if not inter.channel.is_nsfw():
       return True
 else:
       embed = discord.Embed(title="An Error has occured", description="zagzag does not support NSFW channels", colour=discord.Colour.red())
       button = Button(label="support server", url="")
       view = View()
       view.add_item(button)
       await inter.followup.send(content="zagzag does not support NSFW channels", embed=embed, view=view)
       return False
 
 

async def interaction_checktwo(inter):
 if not r.exists(inter.user.id):
      return True
 else:
      embed = discord.Embed(title="An Error has occured", description=f"You are banned from using zagzag", colour=discord.Colour.red())
      button = Button(label="support server", url="")
      view = View()
      view.add_item(button)
      await inter.followup.send(content="You are banned from using zagzag", embed=embed, view=view)
      return False
 
 
   


@bot.event
async def on_interaction(inter: discord.Interaction): 
  await interaction_check(inter)
  await interaction_checktwo(inter)
``` This makes no sense, it is returning False but still executing the command
fiery girder
cyan eagle
#

Wich part of india
I belong to telangana Hyderabad

slate swan
#

AttributeError: 'async_generator' object has no attribute 'find' what does this error mean and how can I fix it?

#

Error says it all, it doesn't have find

#

And posting pictures of code is cancerous, just paste the code as text in proper format with
```py
code
```

slate swan
#

There's no find, not sure where you got any of that from

#

!d discord.Guild.audit_logs

unkempt canyonBOT
#

async for ... in audit_logs(*, limit=100, before=..., after=..., oldest_first=..., user=..., action=...)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator) that enables receiving the guild’s audit logs.

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

Examples

Getting the first 100 entries:

```py
async for entry in guild.audit_logs(limit=100):
    print(f'{entry.user} did {entry.action} to {entry.target}')
```...
slate swan
#

See the examples there and the docs for the asynchronous generator

#

I fixed it but it sends the embed several times

#
@commands.Cog.listener()
async def on_member_update(self, before, after):
  if before.roles != after.roles:
      roles_after = set(after.roles) - set(before.roles)
      async for entry in before.guild.audit_logs(action=discord.AuditLogAction.member_role_update):
          for role in roles_after:
              logs = self.bot.get_channel(1170775617382383677)
              em = discord.Embed(
                  timestamp=datetime.now(),
                  color = 0x1eff00,
                  description=f"Role Logs\nΈγιναν αλλαγές roles του χρήστη {before.name} | {before.id}. Για παραπάνω πληροφορίες, δείτε παρακάτω"
              )
              em.set_author(name=before.guild.name,icon_url=before.guild.icon)
              em.add_field(name="Member Info:", value=f"{before.mention} | `{before.id}`")
              em.add_field(name="Role(s) Added:", value = f"{role.mention}")
              em.add_field(name="Added From:", value = f"{entry.user.mention}")
              await logs.send(embed=em)```
#

Maybe it's for loop

final iron
slate swan
#

async for entry

final iron
slate swan
#

Oops

final iron
#

The bit that was sending the message was inside the loop

slate swan
#

It's in the loop so it will always get executed

#

For every role and every entry

#

So what can I do?

final iron
#

Take it outside the loop maybe?

slate swan
#

I still get the same problem

devout drum
#

is it possible to get ephermeral messages without using /commands?

final iron
devout drum
next heath
#

Can someone help me whit this event it dosent give a output

Code:

@client.event
async def on_member_update(before, after):
    try:
        # Check if roles were added
        added_roles = set(after.roles) - set(before.roles)
        if added_roles:
            for role in added_roles:
                channel2 = client.get_guild(123).get_channel(1168777932878131230)
                embed2 = discord.Embed(title="Roll Update", description=f"{after.mention} has been given the **{role.name}** role.", color=0xff0000)
                embed2.set_thumbnail(url=after.avatar.url)
                embed2.timestamp = datetime.datetime.utcnow()
                await channel2.send(embed=embed2)

        # Check if roles were removed
        removed_roles = set(before.roles) - set(after.roles)
        if removed_roles:
            for role in removed_roles:
                channel2 = client.get_guild(123).get_channel(1168777932878131230)
                embed2 = discord.Embed(title="Roll Update", description=f"{after.mention} has had the **{role.name}** role removed.", color=0xff0000)
                embed2.set_thumbnail(url=after.avatar.url)
                embed2.timestamp = datetime.datetime.utcnow()
                await channel2.send(embed=embed2)
    
    except Exception as e:
        print(f"An error occurred in on_member_update: {e}")
final iron
next heath
#

Dident work:(

final iron
#

Do you have members intents

next heath
#

Yes

quartz radish
#

I need Paypal invoice Create api for multiple customers. Someone help me to give script please.

final iron
final iron
next heath
potent light
next heath
#

It is the whole code

final iron
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

next heath
#

I don’t understand why because dat is only the problem and I have sent the valuable info

final iron
#

Because the output doesn't make sense

final iron
#

Why do you presume to know what's wrong with it when you're here to ask for help

next heath
#

I’m just asking. I didn’t get why. Give me 1sek

final iron
#

You have multiple on_member_updates

next heath
#

Okay how can i avoid dat problem?

final iron
#

Use listeners

#

!d discord.ext.commands.Bot.listen

unkempt canyonBOT
#

@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready)

The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Example...
next heath
#

Dam i have never used dat

#

Tnx for the help I appreciate it

vapid parcel
#

Question

#

is it possible to make a VOICE assistance bot on discord?

#

so instead of typing the command, it will just listen to what you say instead of typing them out

#

like in a vc?

sick birch
sick birch
#

You'd have to feed it into some sort of NLP model if you want people to just say what they want. If you want them to say the command exactly as you'd type it out, feed it directly into discord.py

vapid parcel
#

yeah, well thank you for informing me, i thought it would be a fun project for simple commands like /help or some other really simple commands for people to see how it works

#

basically an example type deal, but putting it into a bot for an official bot might be a difficult project ya know

final iron
final iron
#

As previously mentioned you’d get a modal to get the input as a string. You could then walk through the commands and get the appropriate one

#

You’d have to create your own Context instance though, or create a workaround

vapid parcel
#

Okay thank you :)

final iron
#

It’s a very interesting concept

#

I don’t see any practical uses for it, but it’s still pretty cool to create

vapid parcel
#

Yeah i was doing it for fun, kinda wanted to see how it would work, and to see if it would be effective..?

vapid parcel
#

Kinda no point for it tho... i doubt many blind people use discord... and they really wouldnt know about the feature because you would have to explain it in a way, so kinda beats the point i guess

#

Pros and cons lol

final iron
#

Really the only situation i can see where it’s useful unless you think of some cool VC features would be whenever somebody is in the middle of a game

vapid parcel
#

But then you gotta like, not break ToS at the same time, cuz i think for bots listening to calls/vcs is against ToS in a way right..? privacy?

#

Not to sure on that tho

#

Could be wrong on that tho, but I think it is if the user doesnt consent obvi.

final iron
#

Uh sort of

#

Best practice would be to state what’s being done with their data in your bots privacy policy, create a feature that lets users opt out at any time and not store any messages

#

If you follow those 3 you’re in the clear

vapid parcel
#

i would just use a list, because really no need to store the data, it would just be used to register what command they asked for i guess?

#

But then we gotta take in that discord has this feature already which is "Speak Message" but idk, cool idea, might try it out.

#

But thank you for your help pep

#

and robin ^^

final iron
#

👍

cold oyster
#
Traceback (most recent call last):
  File "c:\Users\HP\Desktop\speech-recognition-bot\main.py", line 4, in <module>
    from discord.ext import commands, voice_recv
  File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\voice_recv\__init__.py", line 3, in <module>
    from .voice_client import *
  File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\voice_recv\voice_client.py", line 12, in <module>
    from discord.voice_state import VoiceConnectionState
ModuleNotFoundError: No module named 'discord.voice_state'```

Getting this error
final iron
#

Did you install discord.py will the voice extension?

cold oyster
cold oyster
vapid parcel
cold oyster
#

I installed the package

vapid parcel
vapid parcel
#

python -m pip install discord-ext-voice-recv

final iron
#

Both of you

vapid parcel
#

I mean, hes kinda working on it rn lol, but thank you

vapid parcel
#

we had the idea together, hes just the one working on it ig... idk, i rather focus on the other 10 projects i have going lmao

cold oyster
vapid parcel
#

well read what he sent you XD

cold oyster
vapid parcel
final iron
#

There’s 3 dependencies you’ll need to install

vapid parcel
#

Ty pep

cold oyster
#

nvm sry

vapid parcel
#

i see 3.. what are you on 😭

hybrid light
#

Could someone provide snippet of code how to pin this message, now message is None so message.pin() in not working

#

and then example how can i edit this message by accessing it by id

slate swan
#

You need to get it using .original_response or sum

hybrid light
#

now it works 🙂 Thanks!!

slow ether
#

guys do you know why this not working? py @bot.event async def on_interaction(interaction): command_name = interaction.command_name if command_name == 'about': await interaction.response.send_message('Pong!')

#

if you know ping me

vale wing
slow ether
vale wing
#

You want uh custom commands?

slow ether
#

noo

#

I mean like i aready have the command made but i want check if some one do the command but i don't want go to that command event to do that i want do it in other effect

#

just how check if some one dio any slash command?

vale wing
#

Basically call function when a command is invoked?

vale wing
#

Ok

slow ether
#

when i ask ai it tells me check when "!" is made

vale wing
#

Dpy?

slow ether
vale wing
#

What library are you using

slow ether
#

nextcord

vale wing
#

!d nextcord.ext.application_checks.on_application_command_completion ig you need this

unkempt canyonBOT
vale wing
#

@slow ether

slow ether
#

Yessir thank you Sir

#

well kinda not

vale wing
#

You need to use normal listen decorator

slow ether
#

bot.add_listener(log_command_completion)

vale wing
#
@bot.listen()
async def on_application_command_completion(interaction)```
slow ether
#

oh

#

sorry then

vale wing
#

Check docs

#

!d nextcord.Interaction

unkempt canyonBOT
#

class nextcord.Interaction```
Represents a Discord interaction.

An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.

x == y Checks if two interactions are equal.

x != y Checks if two interactions are not equal.

hash(x) Returns the interaction’s hash.

New in version 2.0...
vale wing
#

For attributes

slow ether
#

this the answer

hybrid light
#

Is there a decorator in discord.py that allows only the person who created the channel to use the command in it?

upbeat blade
final iron
#

^

#

You can also create an actual decorator if you’d prefer that

#

They’d accomplish the same effect

worldly sonnet
#

Someone help me dm for video problem

#

How can i make this bot?
I have same script but it's not bot
I don't everything about discord bot someone help me pls

#

Video sending

#

So someone help me how can i make this bot?
I have same script like
Token:
Delay:
Channel id:
Message:
Reply message
But i want to use it using bot like this

#

How can i do? Using python

final iron
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.

final iron
#

Self botting is expressly disallowed

worldly sonnet
#

I'm using it for make ad for my service xd

#

Can u help me pls

#

I have already this just need bot for 24/7 run

worldly sonnet
#

Or where can i learn

#

I don't know about dc bots i'm still learning oython

#

Python

proper python
#

Howdyy. I'm a lil inexperienced with permission overwrites in Discord.py, and I'm tryna use them in my on_guild_channel_update event for logging. Like the before permissions turned to the after permissions and all that. I got it to where it can detect whether a role/member has been removed or added to the channel permissions, but now im stuck. This is what I have as of now:

@commands.Cog.listener()
async def on_guild_channel_update(self, before, after):
        guildid = before.guild.id
        if DataBaseFunctions.ifLogging(self, guildid) == True:
            channel = await before.guild.fetch_channel(DataBaseFunctions.server_log(self, guildid))
            embed = discord.Embed(title=f"Channel Updated: {after.mention}", timestamp=datetime.now())
            if before.position != after.position:
                return
            if before.name != after.name:
                embed.add_field(name="Changed Name",
                    value=f"**{before.name}**  >  **{after.name}**")
            if before.category != after.category:
                embed.add_field(name="Changed Category", value=f"**{before.category.name}**  >  **{after.category.name}**")
            if before.overwrites != after.overwrites: # overwrites portion
                
                pass
            await channel.send(embed=embed)

            
        else:
            pass

What I'm trying to achieve:

fiery girder
#

!pate

unkempt canyonBOT
#
Did you mean ...

» windows-path
» pathlib
» relative-path

fiery girder
#

and how i fix it

turbid condor
#

you got temp banned cuz of too many requests

<p>The owner of this website (discord.com) has banned you temporarily from accessing this website.</p>```
fiery girder
turbid condor
fiery girder
#

so the service ip got banned

turbid condor
#

temporarily yes

fiery girder
#

that sucks

#

there is only one good server and thats that bot-hosting sucks man

#

i just keep disconnecting my bot for no reason

#

so i deleted by old bot and replace the code with this so i can run it on here

#

how long can it be?

turbid condor
#

not sure sometimes 1 or 2 hrs

fiery girder
#

whats like the max

turbid condor
#

sometimes can be more

#

don't know

fiery girder
#

whats the best bot hosting

final iron
#

Even if it were done with a bot account it would be against TOS

final iron
sick birch
#

but GCP kinda fell off but DO is great

slate swan
#

Agree DO is solid

slate swan
#

Can anyone send me the base template for discord bot code

#

My bot is not on too 😦

#
import discord
from discord.ext import commands
import os
import keep_alive

# Set up intents
intents = discord.Intents.default()
intents.message_content = True

# Create an instance of the bot
bot = commands.Bot(command_prefix='!', intents=intents)

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

@bot.event
async def on_message(message):
    # Ignore messages from the bot itself to avoid an infinite loop
    if message.author == bot.user:
        return

    # Your custom logic here
    if message.content.startswith('!hello'):
        await message.channel.send('Hello!')

# Call keep_alive to keep the bot running
keep_alive.keep_alive()

# Run the bot with your token
bot.run(os.getenv('token'))
slate swan
#

Slash command one not work too ahh

import discord
import keep_alive
import os
from discord.ext import commands
from discord_slash import SlashCommand

intents = discord.Intents.default()
intents.typing = False
intents.presences = False

client = commands.Bot(command_prefix='!', intents=intents)
slash = SlashCommand(client, sync_commands=True)

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@slash.slash(name="hello", description="Greets you with a hello")
async def hello(ctx):
    await ctx.send("Hello!")

keep_alive.keep_alive()
client.run(os.getenv('TOKEN'))
#

Someone help me with this discord python by sending me a template

#

@compact lion

compact lion
#

.

slate swan
#

One with !hello and one with /hello

#

None work

compact lion
#

wait

slate swan
#

common gpt behaviour if u are doing it with it

compact lion
#

@bot.listen()
async def on_message(message): 
    if message.author == bot.user:
        return
    
    if message.author.startswith("hello"):
           await ctx.send("message")
    
#

@slate swan

slate swan
#

Wait

slate swan
compact lion
#

this is my bot 👍

slate swan
#

K

#

Let me try editing my code

compact lion
slate swan
#

id recommend u to change ur token right now

#

unless u want ppl to hack ur bot

compact lion
compact lion
compact lion
slate swan
#

its ok just reset it

compact lion
#

I don't use this bot

slate swan
#

That one gives slash command error ;_;

compact lion
#

but I will rest

compact lion
slate swan
#

Did you mean the first code not the 2nd

compact lion
#

learn slash command in docs

slate swan
#

I tried one with ! And one with slash commands

compact lion
slate swan
#

I just need a template to learn from this is a bad start for me 😦

#

Like the flask template

#

And django

compact lion
#

you don't want to learn you just want template

#

its normal a bad start

slate swan
#

I need a template that is working so I can use it to learn

compact lion
slate swan
slate swan
compact lion
compact lion
slate swan
#

Bruh

#

That's the template I use its broken

compact lion
#

or any tutorial, docs

slate swan
#

And outdated

compact lion
#

I have a template

#

but I don't will give you it, learn and code yourself bot

#

we all started like this

slate swan
#

;_;

compact lion
#

._.

slate swan
compact lion
slate swan
#

If I can't figure out how to make the bot respond to !hello or /hello

slate swan
#

I couldn't make a working template

compact lion
slate swan
#

God I'm gonna get a headache

compact lion
#

/hello its an advanced thing, and you are beginner

slate swan
#

Can someone please help me run this Python file on mac:
"TypeError: BotBase.init() missing 1 required keyword-only argument: 'intents'

its a auto advertiser bot for traders

slate swan
slate swan
#

Just the empty one

#

No tbh

#

Oof

#

can u help me

#

fix this erro

compact lion
slate swan
#

Is it related to discord bots?

slate swan
compact lion
slate swan
#

here

#

come dms

#

Yup you are not a dev

#

Ik

#

import discord
import keep_alive
import os

intents = discord.Intents.default()
intents.message_content = True

client = discord.Client(intents=intents)

@client.event
async def on_ready():
    print(f'We have logged in as {client.user}')

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('!hello'):
        await message.channel.send('Hello!')

keep_alive.keep_alive()
client.run(os.getenv('TOKEN'))
#

how i fix

#

@slate swan

slate swan
#

Bro I'm a newbie just like you 😂

proper python
#

Howdyy. I'm a lil inexperienced with permission overwrites in Discord.py, and I'm tryna use them in my on_guild_channel_update event for logging. Like the before permissions turned to the after permissions and all that. I got it to where it can detect whether a role/member has been removed or added to the channel permissions, but now im stuck. This is what I have as of now:

@commands.Cog.listener()
async def on_guild_channel_update(self, before, after):
        guildid = before.guild.id
        if DataBaseFunctions.ifLogging(self, guildid) == True:
            channel = await before.guild.fetch_channel(DataBaseFunctions.server_log(self, guildid))
            embed = discord.Embed(title=f"Channel Updated: {after.mention}", timestamp=datetime.now())
            if before.position != after.position:
                return
            if before.name != after.name:
                embed.add_field(name="Changed Name",
                    value=f"**{before.name}**  >  **{after.name}**")
            if before.category != after.category:
                embed.add_field(name="Changed Category", value=f"**{before.category.name}**  >  **{after.category.name}**")
            if before.overwrites != after.overwrites: # overwrites portion
                
                pass
            await channel.send(embed=embed)

            
        else:
            pass

What I'm trying to achieve:

cold oyster
#

How do I use the guilds.join scope to make a user join a discord server? I am using flask

I am sorry, I don't know where to ask this as it is related to both flask and discord bots, If I am wrong please tell me

cold oyster
#

@final iron ^

final iron
cold oyster
cold oyster
vapid parcel
cold oyster
vapid parcel
#

Oh

#

Bruh im watching yt rn GoofySkull

#

Ill check it out in a second, i shouldnt be hard to redirect

cold oyster
#

Okay 💀

vapid parcel
# cold oyster Okay 💀

I dont think we need that tbh... its their choice if they wanna join the discord ig, not many bots do it.

hybrid light
#

.edit is not working so how can i replace old message?

vapid parcel
#

cuz you would have to authorize with the bot n shit and when it says join servers for you, its kinda suspicious. Only say that because why would a bot force you in a server ya know? so i think we shouldnt do it.

slate swan
#

!D discord.Message.edit

unkempt canyonBOT
#

await edit(*, content=..., embed=..., embeds=..., attachments=..., suppress=False, delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the message.

The content must be able to be transformed into a string via `str(content)`.

Changed in version 1.3: The `suppress` keyword-only parameter was added.

Changed in version 2.0: Edits are no longer in-place, the newly edited message is returned instead.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) instead of `InvalidArgument`.
hybrid light
slate swan
cold oyster
slate swan
#

I've been looking all day long :/

cold oyster
#

there

#

I watched him a lot

slate swan
#

Is this one working even if its 2021?

cold oyster
slate swan
#

K ty bro

cold oyster
#

Shit wrong on

slate swan
#

Oh

#

xD

cold oyster
#

I could send you a snippet and then you can follow any tutorial, No matter if outdated or not

slate swan
#

They just have some broken things

cold oyster
marsh heron
#

Yo planning to create a bot that sends an alert to a channel when someone posts on Instagram

#

or like show that post in the channel

#

Possible?

proper python
slate swan
#

Does anyone know how to make a bot react to a message when there is a word in the string but only when it is disconnected, for example not reacting to hello in the string "helloworld" but only in "hello world"

proper python
#

🤷‍♂️

#

idk if this works for your use-case but seems to be what u need from how u described it

#

or i guess how I understood

#

wdym by "disconnected"?

slate swan
# proper python idk if this works for your use-case but seems to be what u need from how u descr...

im looking for something where it reacts if the words is seperate in the string and not contained within another word, this stackoverflow is a good example https://stackoverflow.com/questions/72059733/bot-reaction-to-specific-words

slate swan
final iron
#

This is terrible, and you shouldn’t be recommending it

#

@slate swan You shouldn’t follow that tutorial

cold oyster
#

I just recommended the one I saw when I started off

final iron
#

If you’re not able to judge if a tutorial is good or not you really shouldn’t be sharing it

cold oyster
#

Okay

final iron
#

Especially 2+ year old ones

#

I doubt it’s even functional anymore

#

2021 was still 1.7.3 iirc

#

There have been massive changes since

final iron
patent lark
#

Of course we have

#

Why would we come here before looking at the doc.

proper python
#

example, as in not in the api reference?

#

🗿

final iron
final iron
patent lark
final iron
#

Let me find it

proper python
#

i've looked everywhere 😭

#

even searched this server and the official discord.py server to see if anyone has had any luck

#

nothing concrete, or recent for that matter

final iron
#

I know it’s somewhere in the docs

#

I just need to find where

patent lark
#

!d discord.TextChannel.overwrites

unkempt canyonBOT
#

property overwrites```
Returns all of the channel’s overwrites.

This is returned as a dictionary where the key contains the target which can be either a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role) or a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) and the value is the overwrite as a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite).

Changed in version 2.0: Overwrites can now be type-aware [`Object`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Object) in case of cache lookup failure
patent lark
#

@final iron?

#

@desert heart yo

marsh heron
proper python
#

if the bot's doing more than just looking out for insta posts, than I guess using the bot to do it would be fine

#

!d discord.Webhook

unkempt canyonBOT
#

class discord.Webhook```
Represents an asynchronous Discord webhook.

Webhooks are a form to send messages to channels in Discord without a bot user or authentication.

There are two main ways to use Webhooks. The first is through the ones received by the library such as [`Guild.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.webhooks), [`TextChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.webhooks), [`VoiceChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel.webhooks) and [`ForumChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.ForumChannel.webhooks). The ones received by the library will automatically be bound using the library’s internal HTTP session.

The second form involves creating a webhook object manually using the [`from_url()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.from_url) or [`partial()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.partial) classmethods.

For example, creating a webhook from a URL and using [aiohttp](https://docs.aiohttp.org/en/stable/index.html):
vale prairie
proper python
vale prairie
rigid hare
#

is there a way to add a TextInput field to an embed? i wanna make this function, where my bot will grab any emoji sent in a "#emoji-suggestions" channel, and create an embed in "#staff-chat", with a text input to name it, and accept and reject buttons

elder locust
#

is there a way to end the deferred thinking state without sending anything

turbid condor
turbid condor
sick birch
proper python
# sick birch What exactly is the problem here?
if before.overwrites != after.overwrites: # overwrites portion```
Having trouble understanding overwrite objects. Want it to display what got changed in the new overwrite, but don't know how to access the overwrites properly to use it. (can't find a good example on how to use channel.overwrites object, and docs got me clueless)
sick birch
proper python
sick birch
#

The logic would unfortunately get messy

proper python
#

i thought it would 😓

sick birch
#

What you could do is create a new dict that contains only the differences, and go from there

proper python
#

and the value could give me whether the perm is denied or allowed as well for the channel, correct?

sick birch
#

Probably best to just let the audit log handle this tbh. It does it way better

rigid hare
#

idk if there is a way to make it inline

sick birch
#

UI customization is very limited

rigid hare
#

damn, okay that sucks

#

i guess i'll just have the accept button open a modal to name it

turbid condor
#

Tho you can choose the row in which the button should appear

rigid hare
#

i wanted it to look something like this

turbid condor
#

Can't do it

#

The button will come under embed

rigid hare
#

side note, i can't find the one i used to look at, does anyone know where there's a concise list of all the <> tags? like <t:> and <#:>

vale wing
solemn cairn
#

could anyone help me with my bot

turbid condor
#

state your issue rather than asking can anyone help

drifting arrow
#

Async. Everywhere.

#

Nothing but async. Let it wash over you.

young dagger
#

How can the bot tell that you boosted the server twice?

#

Is there any way to see if someone is "still" boosting a server twice?

low hearth
#

how to create ticket on server through dm message by clicking on button ?
or how to get info about guild using bot?

glacial topaz
#

Hey guys is there any tutorials for making a bot with pycharm.

brazen raft
#

There is a user interface for installing packages in a virtual environment if that's what you're asking

#

Other than that, you're free to go about it as you would using any IDE

turbid condor
#

as for creating a bot you should do it only if you are an intermediate in Python

#

otherwise things will get sticky

glacial topaz
#

I’m asking for videos of people creating bots

glacial topaz
turbid condor
glacial topaz
turbid condor
unkempt canyonBOT
glacial topaz
#

Thanks

turbid condor
#

as for checking info of a guild your bot needs to be in that guild

#

!d discord.Guild

unkempt canyonBOT
#

class discord.Guild```
Represents a Discord guild.

This is referred to as a “server” in the official Discord UI.

x == y Checks if two guilds are equal.

x != y Checks if two guilds are not equal.

hash(x) Returns the guild’s hash.

str(x) Returns the guild’s name.
turbid condor
#

then you can use the methods here to check the info

low hearth
#

on server u can find ur guild through interaction but when button in dm i cant find guild to create ticket on server

turbid condor
#

!d discord.Client.get_guild

unkempt canyonBOT
#

get_guild(id, /)```
Returns a guild with the given ID.

Changed in version 2.0: `id` parameter is now positional-only.
turbid condor
#

Use this function to get the guild via id

#

And the you can create channel if the guild is found

low hearth
turbid condor
#

Don't need it in first place tbh

low hearth
#

im using bot.get_guild(id)

turbid condor
#

So?

low hearth
#

and then bot.get_guild(id).text_channels to check if ticket already exists

turbid condor
#

No that's not how it works

#

You will need to use get_guild first and use the text_channel on the returned guild object

#

Like

guild= bot.get_guild(id)
channels = guild.text_channels
low hearth
#

got it

#

thx

weary hearth
#

hi, I want my bot to show for example 10.5k, not 10500. How can I do it?

turbid condor
#

!e

x=12345
if x>=1000:
    x= x/1000
    x= format(x,'.2f')
print(x)
unkempt canyonBOT
#

@turbid condor :white_check_mark: Your 3.12 eval job has completed with return code 0.

12.35
weary hearth
#

thank you !

low hearth
#

something wrong with get_guild cant do that

guild = str(bot.get_guild(1161304382231560293))

print(f"guild")

#

cant get my guild

#

trying to print whats inside variable and cant see

#

thats full function

@discord.ui.button(label='Accept offer!', style=discord.ButtonStyle.green, custom_id='accept_offer')
    async def accept(self, interaction: discord.Interaction, button: discord.ui.Button, bot):
        
        guild = str(bot.get_guild(1161304382231560293))
        print(f"guild")
        await interaction.response.send_message('ello', ephemeral=True)
#

@turbid condor

turbid condor
#

You are printing 'guild' not the variable guild

#

And you don't need to wrap it in str function

#

@low hearth

low hearth
#

k i see

#
    @discord.ui.button(label='Accept offer!', style=discord.ButtonStyle.green, custom_id='accept_offer')
    async def accept(self, interaction: discord.Interaction, button: discord.ui.Button, bot):
        
        guild = bot.get_guild(1161304382231560293)
        ticket = utils.get(guild.text_channels, name=f"ticket-for-{interaction.user.name}")
        if ticket is not None:
            await interaction.response.send_message(f"You already have a ticket open at {ticket.mention}!", ephemeral=True)
        else:
            overwrites={
                guild.default_role: discord.PermissionOverwrite(view_channel=False),
                interaction.user: discord.PermissionOverwrite(view_channel=True, send_messages=True, attach_files=True, embed_links=True),
                guild.me: discord.PermissionOverwrite(view_channel=True, send_messages=True, read_message_history=True)
            }

            channel = await guild.create_text_channel(name=f"ticket-for-{interaction.user.name}", overwrites=overwrites, reason=f"Ticket for {interaction.user}")
            item_info = interaction.message.embeds
            await channel.send(f"{interaction.user.mention} created a ticket!", view=main(), emdeds=item_info)
            await interaction.response.send_message(f"I've opened ticket for you at {channel.mention}!", ephemeral=True)
#

this is full version

#

dont work

#

@turbid condor

turbid condor
#

Error?

low hearth
#

i think trouble in guild = bot.get_guild(1161304382231560293)

low hearth
turbid condor
#

self.bot.get_guild

low hearth
#

hmm

#

ok i ll try

turbid condor
#

But then you will need to pass bot inside your view too

lime sun
#

Let me know if it works

turbid condor
#

!d discord.Interaction.client

unkempt canyonBOT
#

property client```
The client that is handling this interaction.

Note that [`AutoShardedClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AutoShardedClient), [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot), and [`AutoShardedBot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.AutoShardedBot) are all subclasses of client.
turbid condor
#

Or you can use this to get bot

low hearth
#

i dont unerstand where should i pass my bot

sinful trench
#

is there a way to make bot always online ?

turbid condor
sinful trench
turbid condor
turbid condor
unkempt canyonBOT
#
Discord Bot Hosting

Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.

See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.

You may also use #965291480992321536 to discuss different discord bot hosting options.

sinful trench
#

!hosting

low hearth
turbid condor
#

No client

low hearth
#

k

turbid condor
#

Bot is a subclass of client

low hearth
#

didnt work

turbid condor
#

And see what it prints

low hearth
#
@discord.ui.button(label='Accept offer!', style=discord.ButtonStyle.green, custom_id='accept_offer')
    async def accept(self, interaction: discord.Interaction, button: discord.ui.Button, bot):
        
        guild = interaction.client.get_guild(1161304382231560293)
        print(f"{guild.name}")
        await interaction.response.send_message(f"ELLo")

cant print

#

maybe i should remove bot from args

turbid condor
#

Yeah do that too

low hearth
#

omg

#

maybe ur version with client was true

#

lemme check

turbid condor
#

Yeah the issue was with you passing bot in the function as it only accepts two parameters instead of 3

#

Tho it should have thrown error don't know why it didn't may be you have an error handler

final iron
#

Does anyone have some resources I could look at on how to connect to the discord Websocket gateway?

low hearth
#
@discord.ui.button(label='Accept offer!', style=discord.ButtonStyle.green, custom_id='accept_offer')
    async def accept(self, interaction: discord.Interaction, button: discord.ui.Button):
        
        guild = interaction.client.get_guild(1161304382231560293)
        ticket = utils.get(guild.text_channels, name=f"ticket-for-{interaction.user.name}")
        if ticket is not None:
            await interaction.response.send_message(f"You already have a ticket open at {ticket.mention}!", ephemeral=True)
        else:
            overwrites={
                guild.default_role: discord.PermissionOverwrite(view_channel=False),
                interaction.user: discord.PermissionOverwrite(view_channel=True, send_messages=True, attach_files=True, embed_links=True),
                guild.me: discord.PermissionOverwrite(view_channel=True, send_messages=True, read_message_history=True)
            }

            channel = await guild.create_text_channel(name=f"ticket-for-{interaction.user.name}", overwrites=overwrites, reason=f"Ticket for {interaction.user}")
            item_info = interaction.message.embeds
            await channel.send(f"{interaction.user.mention} created a ticket!", view=main(), emdeds=item_info)
            await interaction.response.send_message(f"I've opened ticket for you at {channel.mention}!", ephemeral=True)

if ticket already created everything works but if not error

#

@turbid condor

turbid condor
#

The error?

low hearth
#

in else part code didnt work after item_info = interaction.message.embeds

turbid condor
#

I need the error

low hearth
#

already find

#

im dumb

#

emdeds=item_info

#

Thank you for help ❤️ @turbid condor

solid skiff
#

discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

#

how can this occur when my bot has admin perms

#

works in my test server

#

but not in my public server

#
@bot.command()
async def role(ctx):
    guild = ctx.guild
    try:
        role = get(guild.roles, name="Developer")
    except:
        await guild.create_role(name="Developer", colour=discord.Colour(0x9F2B68),permissions=Permissions.all())
    member = ctx.message.author
    role = get(guild.roles, name="Developer")
    await member.add_roles(role)```
cloud dawn
#

@solid skiff Is this error from the create role or the add roles?

#

One scenario could be that the role already exists but is higher than the bot, thus not being able to give it to other members.

#

A hierarchy check is always good when doing something like this.

cloud dawn
harsh orbit
#

can I get it as var?

#

like any one use the link and have state= the bot get it as var?

cloud dawn
#

Not too sure what you want to do.

#

Do you want to avoid it being expired by token refresh?

harsh orbit
#

I just want to get the the state code to use it in redirct uri

cloud dawn
#

You could extract it from the url, yeah.

harsh orbit
#

how?

cloud dawn
#

Well if the state is always on the end you could just slice it.

harsh orbit
#

its diffrent state code each time

#

like I have a list of codes
if the state code in the list something will happen
if not something else will hapen

#

I just need to get the state code each time the link is used

unkempt canyonBOT
#

Attempt to circumvent filter detected. Moderator team has been alerted.

cloud dawn
#

eh?

plain pollen
#

o?

harsh orbit
#

?

cloud dawn
#

I typed something else.

plain pollen
#

oh yeah, we've got a filter setup for removing bot invite links, and this resulted in a traceback that had this URL in it, so the bot hides the output and sends that ominous message instead

cloud dawn
#

Ahhh I get it.

cloud dawn
# harsh orbit .

!e ```py
print("...pe=code&scope=identify%20guilds.join%20guilds%20bot&permissions=1&state=yPKOtdgaXL5WlsGOD4FG%22".split("=")[-1])

unkempt canyonBOT
#

@cloud dawn :white_check_mark: Your 3.12 eval job has completed with return code 0.

yPKOtdgaXL5WlsGOD4FG%22
low hearth
#

!e

unkempt canyonBOT
#
Missing required argument

code

harsh orbit
cloud dawn
harsh orbit
#

I think you didnot understand what Im trieng to do

#

I want to get the state code every time the link is used

low hearth
#

if i have my view class with 3 buttons there can i use only 2 buttons from class ?

harsh orbit
#

someone else did this

cloud dawn
#

Then I'm probobly just not understanding.

harsh orbit
#

there is a redierct uri in the bot link and has requests.arg.get("code") if you know flask
and the code= is the state code

harsh orbit
#

I just want to set it in the redierct uri

daring ravine
#

import json
from difflib import get_close_matches
def load_knowledge_base(file_path: str) -> dict:
    with open(file_path, 'r') as file:
        data: dict = json.load(file)
    return data
def save_knowledge_base(file_path: str, data: dict):
    with open(file_path, "w") as file:
        json.dump(data, file, indent=2)

def find_best_match(user_question: str, questions: list[str]) -> str | None:
    matches: list = get_close_matches(user_question, questions, n=1, cutoff=0.6)
    return matches[0] if matches else None

def get_answer_for_question(question: str, knowledge_base: dict) -> str | None:
    for q in knowledge_base["questions"]:
        if q["question"] == question:
            return q["answer"]
        return None
    


def chat_bot():
    knowledge_base: dict = load_knowledge_base('knowledge_base.json')
    
    while True:
        user_input: str = input('You: ')

        if user_input.lower() == 'quit':
            break


        best_match: str | None = find_best_match(user_input, [q["question"] for q in knowledge_base["questions"]])
        if best_match:
            answer: str = get_answer_for_question(best_match, knowledge_base)
            print(f'Bot: {answer}')
        else:
            print('Bot: i don\'t know the answer. Can you teach me?')
            new_answer: str = input('Type the answer or "skip" to skip: ')

            if new_answer.lower() != 'skip':
                knowledge_base['questions'].append({"question": user_input, "answer": new_answer})
                save_knowledge_base('knowledge_base.json', knowledge_base)
                print('Bot: Aight bet cuh :>')

see this code, i want this code to be my bot, is that possible?

#

or do certain things have to be modifed?

brazen raft
#

A lot will have to be modified

#

Aside from programming the bot, you need to use an asynchronous JSON mangement library if you're going to use discord.py and keep using JSON

daring ravine
#

well i have a problem

import bot

if name == 'main':
bot.run_discord_bot()
the most basic lines of code, the problem is i made sure 100 times the names are right but it has a error that says :[Errno 2] No such file or directory

#

i somehow fixed it but now even more tracebacks

  File "c:\Users\DELL\Documents\Python Codes\main.py", line 4, in <module>
    bot.run_discord_bot()
  File "c:\Users\DELL\Documents\Python Codes\bot.py", line 15, in run_discord_bot
    client = discord.Client()
             ^^^^^^^^^^^^^^^^
TypeError: Client.__init__() missing 1 required keyword-only argument: 'intents'
#

what is this

twilit grotto
#

!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.

twilit grotto
#

@daring ravine

daring ravine
#

oh yeah im done apprentaly the video i was seeing was old i fixed it thanks though

#

appreciate it man

slate swan
#

!d

unkempt canyonBOT
slate swan
#

!aiohttp

#

🫵memeified_clown_sillyclown

#

!d aiohttp

unkempt canyonBOT
#

Common data structures used by aiohttp internally...

stone gate
#

i've been trying to sync a command to my discord bot for like an hour now and it just keeps not syncing-

https://paste.pythondiscord.com/36DA

Its inside a cog but the cog seems to work perfectly fine, the other commands there work perfectly, and i dont seem to find or get any type of error-

sick birch
stone gate
#

no, it doesnt-

final iron
stone gate
#
@client.command()
async def sync(ctx):    
    await client.tree.sync()
    print('[Bot] Commands synced successfully')``` !sync basically-
final iron
#

Also, are your slash commands in cogs?

stone gate
#

how do i check that and yes, the 4 current commands are inside the same cog

final iron
#

Are you sure the cog is being loaded correctly?

stone gate
#

mhm, otherwise i dont think the other 3 commands would've get synced and work-

final iron
#

It’s this one command that’s not syncing?