#discord-bots

1 messages · Page 128 of 1

slate swan
#

what

#

what does thatt mean

cloud dawn
#

XDDOS.jar

rustic edge
#

Not sure if this question belongs here, but it's the best fitting place on the server.

What Docker container would I use to run my Python Bot? (I'm on Synology Nas)
And how would I run it on that container?

sick birch
rustic edge
#

I tried that container, couldn't figure out how to run my bot on it.

sick birch
#

What problem were you having?

rustic edge
#

Running the file, also the mount path.

#

For example, I got into the Py console just fine.

sick birch
#

Running the file should just be python <filename>.py

rustic edge
#

Syntax error

sick birch
#

Type exit() first, then run it

rustic edge
#

That kills the server.

sick birch
#

It kills the interactive REPL

rustic edge
#

*container

#

Oh.

sick birch
#

oh you're already inside the container?

rustic edge
#

Yep, Synology

#

Also, happen to know what mount path to use?

sick birch
#

Usually you wouldn't be inside the container doing stuff

rustic edge
#

How else would I do it?

sick birch
#

Give it instructions on how to build your applications and run

#

start the container and let it do its thing

#

that's kind of the whole point of docker :p

rustic edge
#

Where to I put those instructions though

rustic edge
sick birch
rustic edge
#

Which is located at?

sick birch
#

You might want to check out the docker documentation for more information

sick birch
#

you'll have to create it most likely

rustic edge
#

Im so silly

rustic edge
sick birch
#

What do you mean?

rustic edge
#

Nvm

#

i just rememberd i can SSH into my docker

#

mb

#

thanks for you help ❤️

sick birch
rustic edge
#

Yeyep

#

im able to SSH directly into my nas

#

so I can just docker CLI from there

sick birch
#

its mean to just do its own thing

slate swan
#

replit has similar issues with sqlite, it clears the data often as well
just use a proper vps tbh

slate swan
#

bruuuuuUUHHHhhHHHHUHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH

hushed karma
cerulean folio
#

sorry I was outside being busy I just came back, I'll check all this thank you a lot for helping me 1KSF_catblush

slate swan
#

ok im back

hallow marten
#

can nextcord take user input with slash commands in python

slate swan
#

yes, how? look in the examples directory of nextcord's github repo

hallow marten
#

k thanks thts all i needed

slate swan
#

need help checking if theres a space in a string in slash

slate swan
unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.

True
slate swan
#

anyone have any examples of discord py, using buttons with @bot.listen commands.

#

how do i send a embed w/ buttons on a @bot.listen

cloud dawn
#

What event?

slate swan
#

i found out how to make it send embeds

#

but with buttons? i dont know

cloud dawn
#

Why not use slash commands?

slate swan
#

i have a ticket bot

cloud dawn
#

You can just use the View kwarg

slate swan
slate swan
# slate swan example?
class h(discord.ui.View):
    def __init__(self):
        super().__init__()

    @discord.ui.button(label="h", style=discord.ButtonStyle.gray)
    async def h(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_message("ok its done")
        self.stop()

@bot.command()
async def ask(ctx: commands.Context):
    await ctx.send("do u want to sddsfgsdfg", view=h())
    await h().wait()


bot.run(token)
cloud dawn
slate swan
#

but its not @bot command its @ listen

slate swan
slate swan
#

huh

#

read

#

Basically this allows you to listen to multiple events from different places e.g. such as on_ready()

glad cradle
slate swan
cloud dawn
slate swan
#

oh

#

thanks

nocturne compass
#

how do i make my bot respond to a question without using on_message?

feral frost
#

how can i send the message i type back ?

nocturne compass
#

i want my bot to respond to that message they send

slate swan
feral frost
#
@bot.event
async def on_message(msg):
    if msg.author == bot.user:
        # if the author is the bot itself we just return to prevent recursive behaviour
        return
    if msg.content == "$response":

        sent_message = await msg.channel.send("Waiting for response...")
        res = await bot.wait_for(
            "message",
            check=lambda x: x.channel.id == msg.channel.id
            and msg.author.id == x.author.id
            and x.content.lower() == "yes"
            or x.content.lower() == "no",
            timeout=None,
        )

        if res.content.lower() == "yes":
            await sent_message.edit(content=f"{msg.author} said yes!")
        else:
            await sent_message.edit(content=f"{msg.author} said no!")```
Like this but with message being send instead of "yes" or "no"
nocturne compass
slate swan
# nocturne compass
import discord
from discord.ext import commands

intents = discord.Intents.default()

bot = discord.ext.commands.Bot("prefix", intents=intents)

@bot.command(name="name", description="h")
async def name(ctx):
    await ctx.reply("h")
slate swan
nocturne compass
nocturne compass
#

i just need the bot to reply to id a user sends

slate swan
feral frost
#

? author

slate swan
#

!author

feral frost
#

no no you dont understand my question i think

slate swan
#

oh

feral frost
# slate swan msg.author

like you do $respone and it sends a message and i answer with yes or no and it edits it to yes or no bla bla bla but i want it to send the message i send instead of yes or no to be send

feral frost
#

ok

cerulean folio
#
class Question:
    def __init__(self, view):
    self.view = view

    async def ask():
        await self.ctx.send('Hello world', view=view)
        print('View sent with all items')
        self.view.clear_items()
        self.view.stop()
        print('View items cleared and closed')

Hi, since I'm not understanding the proper behavior of View.clear_items() and View.stop(), this case does not work for some reason.

Also there's another case where it doesn't work.
In callback functions this code won't delete the items but will edit the message:

async def callback(self, interaction: Interaction):
        assert self.view is not None

        if self.view.ctx.author.id == interaction.user.id:
            await interaction.response.edit_message(content=self.edit_with)
            self.view.canceled = True
            self.view.clear_items()
            self.view.stop()

but moving self.view.clear_items() above interaction.response.edit_message() will work.

I'm confused bigbrainwobble

slate swan
sick panther
#

what yall think about the new "active developer" badge

cerulean folio
sick panther
#

wdym

#

not sure if thats irony or not lol

cerulean folio
sick panther
#

no lol

#

you just need to have one global application command, and thats it

#

i mean i got a verified bot, but i chose my bot which is specifically for the support server. its just in that server and everything worked as intended

cerulean folio
#

i don't see it lol

sick panther
#

reload your discord client

#

also had that 5min before

cerulean folio
#

oh i see

#

I'll check that another time tbh, I'm more worried by my code not working properly for now lol

sick panther
fading marlin
#

"You are not eligible for the Active Developer Badge" 🥲

sick panther
#

damn

sick panther
slate swan
cerulean folio
cerulean folio
fading marlin
# cerulean folio ```python class Question: def __init__(self, view): self.view = view ...

I'm not understanding the proper behavior of View.clear_items() and View.stop()
View.clear_items removes all items from the current view object. !! It doesn't remove them from the message, you have to edit it to accomplish this !!
View.stop is mostly used with View.wait. View.stop is basically a manual/program timeout

but moving self.view.clear_items() above interaction.response.edit_message() will work.
Yeah, cause you're editing the message after you clear all items

fading marlin
slate swan
#

loooli just create one and use it once, thats all you need

slate swan
sick birch
#

what's good folks

nocturne compass
#

how to fix?

sick birch
slate swan
sick birch
#

There's already a module called "random"

slate swan
#

it was released like idk 2 hrs ago?

sick birch
fading marlin
slate swan
sick birch
#

So not that special then

sick panther
slate swan
#

its ugly as well, wish i could just remove it

sick panther
#

facts

nocturne compass
#

does anyone know i can store lots of numbers in a variable but not write all the numbers

for example 1 to million

slate swan
#

range

#

!d range

unkempt canyonBOT
#

class range(stop)``````py

class range(start, stop[, step])```
The arguments to the range constructor must be integers (either built-in [`int`](https://docs.python.org/3/library/functions.html#int "int") or any object that implements the [`__index__()`](https://docs.python.org/3/reference/datamodel.html#object.__index__ "object.__index__") special method). If the *step* argument is omitted, it defaults to `1`. If the *start* argument is omitted, it defaults to `0`. If *step* is zero, [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "ValueError") is raised.

For a positive *step*, the contents of a range `r` are determined by the formula `r[i] = start + step*i` where `i >= 0` and `r[i] < stop`.

For a negative *step*, the contents of the range are still determined by the formula `r[i] = start + step*i`, but the constraints are `i >= 0` and `r[i] > stop`.
sick birch
nocturne compass
sick birch
#

!d random.randint

unkempt canyonBOT
#

random.randint(a, b)```
Return a random integer *N* such that `a <= N <= b`. Alias for `randrange(a, b+1)`.
nocturne compass
#

im using random libabry

main moth
#

Can someone send me a first step code of python bot so that it reacts if i send hi for example

slate swan
#

!d discord.Client.wait_for

#

oh no wait sorry

slate swan
#

!d discord.Message.add_reaction then use this to add the reaction

unkempt canyonBOT
#

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

Adds a reaction to the message.

The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji").

You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") to do this. If nobody else has reacted to the message using this emoji, [`add_reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") is required.

Changed in version 2.0: `emoji` parameter is now positional-only.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.11)") instead of `InvalidArgument`.
main moth
#

That all does not work

#

Just tryed a simple send message

main moth
# slate swan you can use `on_message` event, and check if message.content is "hi"
import discord
import os

client = discord.Client()

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

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

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

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

why does this now work

slate swan
#

!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. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot 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

intents = Intents.default()
intents.members = True

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

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

main moth
slate swan
#

you didnt load the env

main moth
#
from discord import Intents
from discord.ext import commands
import os

intents = Intents.default()
intents.members = True

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


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

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

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

client.run(os.getenv(TOKEN)

#

Changed to this

slate swan
#

yeah the code is correct, but i said you need message_content intents, not members

main moth
#

Doesnt work also for me

slate swan
main moth
#

how to load it?

slate swan
#

pip install python-dotenv

import dotenv
dotenv.load_dotenv()
main moth
#
from discord import Intents
from discord.ext import commands
import os
import dotenv


dotenv.load_dotenv()

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

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


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

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

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

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

So like this

slate swan
#

yea

#

make sure you enabled the intents from dev portal too or you'll get yeeted

nocturne compass
#

anyone know how i can add letters when using random.randint

main moth
slate swan
main moth
#

Got it

main moth
#

But also the error xD

slate swan
#

did you save after making changes?

main moth
cerulean folio
#

any idea how to achieve this:

class Question:
    def __init__(self, ctx, view, content, embed=None, embeds=None):
        self.ctx = ctx
        self.view = view
        self.embed = embed
        self.embeds = embeds
        self.canceled = False
        self.content = content

    async def question(self) -> Message:
        return await self.ctx.send(
            self.content, view=self.view, embed=self.embed, embeds=self.embeds
        )

    async def check_cancel(self):
          message = await self.question()
        await self.view.wait()
        if self.canceled:
            await message.edit(content=self.content, view=None)
            return True

# Inside another class:
tasks = [
    question_task := asyncio.create_task(await_reportee(self)),
    cancel_task := asyncio.create_task(self.check_cancel()),
]
done_task, pending_task = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)

I want the question() message to remove items if check_cancel() is triggered by the button callback of the view, or if the answer to the question() is right. I would need to pass the output question() to check_cancel() before it outputs which is nonesense :/

I'm kinda lost in OOP it's still new to me lol

main moth
slate swan
# main moth

do you have a proper env setup? show your ,.env file with token removed

main moth
main moth
slate swan
#

what

slate swan
main moth
#

dont know it - never worked with it

slate swan
cerulean folio
slate swan
slate swan
pliant gulch
#

I probably wouldn't do that create_task stuff tbh, you schedule the task to the event loop concurrently, meaning that your question_task or cancel_task could be executed before the other

main moth
#

is there a easier way?

#

if yes i prefer

slate swan
#

just pasting your token there yes

main moth
#

so i can delete load_dotenv

slate swan
#

sure

main moth
#

and the rest with intent?

slate swan
#

it will stay

main moth
#

Works

#

thank you

nocturne compass
#

how do i make my bot respond

#

code here

#

what should i add at the bottom

mighty pilot
#

Thought I answered this question yesterday

main moth
# slate swan it will stay
client = commands.Bot(command_prefix="!", intents=intents)

@commands.command()
async def test(ctx):
    await ctx.send('test')

client.add_command(test)

Why does it now work if i write !test test in the chat?

mighty pilot
#

Do you have an on_message event

slate swan
main moth
#
client = commands.Bot(command_prefix="!", intents=intents)

@commands.event()
async def test(ctx):
    await ctx.send('test')

client.add_command(test)
#

cant find on_message

slate swan
#

what

#

that's not what i asked to do at all

#

some1 help rq

shrewd apex
slate swan
shrewd apex
slate swan
#

no

#

helppp

main moth
shrewd apex
shrewd apex
slate swan
#

user input

silent ermine
#

How do I make the title of an embed a link?

silent ermine
cerulean folio
# slate swan maybe some example could help?

OK I solved it !!! I just struggled managing the flow of data inside my classes but I'm fine now.
Last thing is:

# timeout function of a view
async def on_timeout(self):
    self.clear_items()
    self.stop()
    await self.message.edit(content="Report cancelled due to timeout.", view=self)
    self.canceld = True

that self.message I need it and I don't find a way to get it there lol

slate swan
#

gg Tada

cerulean folio
slate swan
shrewd apex
shrewd apex
unkempt canyonBOT
#

wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.11)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.11)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.11)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
cerulean folio
#

lemme try something jumpKaiyo

waxen igloo
#
    async def setup_hook(self):
        for filename in os.listdir('./cogs'):
            if filename.endswith('.py'):
                await self.load_extension(f"cogs.{filename[:-3]}")
        await self.tree.sync(guild=discord.Object(id=1038882741510488105))

@bot.tree.context_menu(name="Hello", guild=discord.Object(id=1038882741510488105))
async def hello(interaction: discord.Interaction, message: discord.Message):
 await interaction.response.send_message("sup")

don’t say anything about the way i sync because i’m changing it later but the app commands doesn’t work.. my slash commands do just not apps.

shrewd apex
cerulean folio
#

thank youuuuuu I'm so happy omg !

shrewd apex
#

👍

cerulean folio
#

I can't believe I'm DONE

#

I understood the whole system

waxen igloo
shrewd apex
cerulean folio
#

ty so much jumpKaiyo LoveGive

shrewd apex
#

💐

waxen igloo
#

raise TypeError(f'unsupported type annotation {annotation!r}')

TypeError: unsupported type annotation <class 'discord.message.Message'>

#

@shrewd apex …

shrewd apex
#

coz its str and not discord.Message

#

u know what type hints are

waxen igloo
#

@shrewd apex It isnt a slash command

#

its app

shrewd apex
#

🚶

waxen igloo
#

lmaoo

shrewd apex
waxen igloo
shrewd apex
#

I'll just let someone else help u

main moth
#

How can I tell my DIscord bot to address a specific person (name, tagg)? Wouldn't want to tell it by command but by another script so to speak (python)

#

@shrewd apex you know it, i know it xD

shrewd apex
#

see if not a command u can use on_message event if not from discord at all

#

then u would have to make an endpoint/websocket ur bot app is listening to and send data there

main moth
#

wait i will explain it a bit more

unkempt canyonBOT
#

property name```
Equivalent to [`User.name`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.name "discord.User.name")
shrewd apex
#

and .discriminator

main moth
#

I have a script where you can enter a username to which an automatic message (DM) should be sent. How can I send a DM to people in such a way that I make the trigger for the DM with another script, so to speak. Do you understand me?

#

@shrewd apex

shrewd apex
slate swan
#

can someone give me a example of you writing a number, the bot multiplies that number and show it in a embed?

#

hello

cerulean folio
main moth
sick birch
#

hello

cerulean folio
slate swan
#

hello, i am turkish, do you have any turkish people, he will teach me python

cerulean folio
#

thing is that when i edit the message with view=None the view timeout function still edits the message... so I need to stop it

#

Also ```python
class Reportee(Question):
def init(self, ctx: Context):
super().init(ctx, QuestionView(ctx, None, 30, None), AWAIT_REPORTEE_MESSAGE)

when I use `self.view` inside this class it says that it's an Unknown argument, but I passed it to the super class so i'm kinda confused
slate swan
#

aaaa

#

How do you get the bot to save your message in a variable

#

Or wtv

cerulean folio
#
class MyView(View):
    def __init__(self, ...):
        # Content of my view

class Question():
    def __init__(self, ctx, view):
        self.ctx = ctx
        self.view = view

    async def ask(self):
        self.question = await self.ctx.send('Hello...', view=self.view)

class Age(Question):
    def __init__(self, ctx):
        super().__init__(ctx, MyView(...))

    async def await_age(self):
        async def check_answer(self):
            await self.ask()
            # Other things to check

        async def check_cancel(self):
            # Bunch of stuff that check if the cancel button has been clicked, then execute code below 
            self.view.clear_items()
            self.view.stop()
            self.question.edit('... World !', view=self.view)

ask_age = Age(ctx)
ask_age.await_age()

I tried to make a miniature of the structure of my code to explain my problem. So here it seems that self.view inside Age class isn't being accessed for some reason. Why is that?

slate swan
#

does it raise some error?

cerulean folio
cerulean folio
#

I think the problem comes from

async def papa_method(self):
    async def baby_method(self):
        self.view
#

that self being passed to both, I assume it's the class containing these methods right? And it's the same self right?

slate swan
#

well, you are never calling those two function anywhere

#

code= https://paste.nextcord.dev/?id=1668046023263318
i need help with the transcript system.
So basically there both html files (refering to the 2 pictures i sent)
but the one thats like white only collects the message history of the channel
i wanna know how i can make it collect embeds, attachments, channel names, the server name/logo, and have the html file have the same colour as discord.

cerulean folio
#

oh yes yes in my code i do actually

slate swan
#

mind showing full code? self is not needed there at all

#

since its already in the parent function

cerulean folio
cerulean folio
#

so here's the scenario it isn't working:
when I invoke the command s-report, it will ask me an ID
if I put a wrong ID, it will remove the Cancel button from the first message, and send me Invalid ID with a new cancel button in it.
then if I write cancel everything will cancel. but that first message will transform to Cancelled because of time out when it's supposed to be stopped

#

in other words: lines 135 and 136 if you remove them, line 138 will work, and if you activate them, it won't ><

mighty pilot
#

Line 136

#

Also if you want to clear all the items from a view why not just use view=None

mighty pilot
cerulean folio
#

I mean... it doesn really work like i want but it works

mighty pilot
#

Maybe move it below your edit statement?

abstract kindle
#

What does this message mean
[2022-11-10 17:01:40] [INFO ] discord.gateway: Shard ID None has successfully RESUMED session 00ac666ecad2788ba94afebbc6086957.

#

I'm getting it a ton

sick birch
abstract kindle
#

Hmm

#

My pc doesn't go to sleep though

sick birch
#

Nothing to be worried about, it could be on discord's end

#

Disconnects happen a lot

abstract kindle
#

I see

sick birch
abstract kindle
#

It clogs the terminal though :/

sick birch
#

Well that's good

#

The whole point of logs

abstract kindle
#

I suppose

#

they should make it a nicer color than red

#

especially since its just info and not an actual error

mighty pilot
#

can i fetch a single role from my guild

#

or is there a way to see if a user has a role from just the id

#

nvm i think i got it with the search bar

#

...maybe

mental hollow
#

Anyone know why I’m getting this error? I’m can’t seem to find why..

Ignoring exception in on_connect
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 377, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/.local/lib/python3.9/site-packages/discord/bot.py", line 1138, in on_connect
    await self.sync_commands()
  File "/home/container/.local/lib/python3.9/site-packages/discord/bot.py", line 692, in sync_commands
    registered_commands = await self.register_commands(
  File "/home/container/.local/lib/python3.9/site-packages/discord/bot.py", line 570, in register_commands
    data = [cmd["command"].to_dict() for cmd in filtered_deleted]
  File "/home/container/.local/lib/python3.9/site-packages/discord/bot.py", line 570, in <listcomp>
    data = [cmd["command"].to_dict() for cmd in filtered_deleted]
  File "/home/container/.local/lib/python3.9/site-packages/discord/commands/core.py", line 841, in to_dict
    "options": [o.to_dict() for o in self.options],
  File "/home/container/.local/lib/python3.9/site-packages/discord/commands/core.py", line 841, in <listcomp>
    "options": [o.to_dict() for o in self.options],
  File "/home/container/.local/lib/python3.9/site-packages/discord/commands/options.py", line 315, in to_dict
    "type": self.input_type.value,
AttributeError: 'NoneType' object has no attribute 'value'
mighty pilot
#

helps if i have correct id in the first place...

mighty pilot
mental hollow
#

which makes no sense to me

mighty pilot
#

show the applicable part of your code

mental hollow
#

well this happened with my help cmd I think so I’ll show that code

mighty pilot
#

it says the error is in on_connect

#

but if it happened with the help command something there is probably doing something weird

mental hollow
#
@bot.slash_command(description = "View Aziel's current commands.")
async def help(self, ctx: discord.ApplicationContext):
    if not ctx.author.id == 831118106876969021:
        return await ctx.respond("This command is under maintenance.", ephemeral = True)
    pages = [
        discord.Embed(title = "test page 1"),
        discord.Embed(title = "test page 2")
    ]
    await ctx.respond(embeds = pages[0] if isinstance(pages[0], list) else [pages[0]], view = ButtonMenu(pages, 10, ctx.author))
mental hollow
#

so it’s using the default lib one

mighty pilot
#

does it send anything on discord? like the ephemeral message

mental hollow
#

the command isn’t even being registered

mighty pilot
#

do you have other commands that are working?

mental hollow
#

yes, all my other commands are working

mighty pilot
#

do you have a command to sync your commands with discord?

mental hollow
#

no since py-cord does that automatically

#

in the default on_connect event

mighty pilot
mental hollow
#

so I’m thinking it’s failing to register my command therefore raising the error

#

yeah

#

but idk what’s wrong

mighty pilot
#

im not sure, dont use pycord. im sure someone else who knows it better will be in here before too long

mental hollow
#

alrighty, thanks :) although I’ve gotta head off in around 20 mins since it’s almost 1am for me

sweet pilot
#

how'd i use async with to start the bot

#

documentation doesn't properly describe it

mighty pilot
#

to start your bot?

sweet pilot
#

yh

waxen cradle
sweet pilot
#

no it's ok i got it

#
async with self.bot:
    self.loop.create_task(self.bot.start(self.config.token))  # type: ignore
    await self.bot.wait_until_ready()
#

thx anw

waxen cradle
#

how can i make this task run just once a day? as it stands it just runs endlessly

mighty pilot
#

my giveaway bot puts the people who entered the giveaway in a list and pulls winners from that list. i want to give people additional entries for boosting the server, so i add them to the list multiple times for that. how do i prevent the bot from choosing the same person twice?

rugged shadow
mighty pilot
rugged shadow
#

or does your giveaway pick multiple people

mighty pilot
rugged shadow
#

i think what you could do is write a custom random.choice or something like that

waxen cradle
mighty pilot
#

right now its just a random.choice from the list of people with multiple entries. i just dont know how to make sure i get a unique user each time

mental hollow
mighty pilot
#

oh apparently random.sample() doesnt give duplicates

waxen cradle
bright wedge
mental hollow
#

I recieve the error in my console

sweet pilot
#

can I run a bot in a loop provided by me?

dense flower
#

what do you mean by that exactly 😆

sweet pilot
#

rather than bot starting a async loop on it's own

sweet pilot
upbeat gust
sick birch
ionic garden
#

how do i only disable a

#

button for some users

robust fulcrum
dense flower
#

anyone seen this error before?py discord.app_commands.errors.CommandInvokeError: Command 'addpoints' raised an exception: InvalidDocument: cannot encode object: <Member id=914884204926468168 name='amber' discriminator='5807' bot=False nick=None guild=<Guild id=975074982474448947 name='Primetime Flips' shard_id=0 chunked=False member_count=226>>, of type: <class 'discord.member.Member'>
Code worked on my pc but on clients pc it seems to be running into an error?

#

it seems like it's not detecting user "amber" as a discord member yk

sick birch
#

Can you show us your code?

dense flower
#

for sure

sick birch
#
    newData = {
          "_id" : uID,
          "Discord Name" : username,
          "Points" : points
      }
#

you're trying to add the member object itself to the database

#

it doesn't know how to encode it so it's in a format your database supports

#

you want to use username.name instead

dense flower
#

oh ok ill swap that and see if it works, any idea why it was working on my side?

dense flower
#

so strange

sick birch
# dense flower so strange

Forgive me for being crass here, but often when people say something like "this worked on my other machine" or "this worked yesterday" it often didn't or the code when it did work was correct

#

There's no reason for a cross platform language like Python to work on one platform but not another

#

I'm not blaming you of course it's just something common that I see

dense flower
#

it worked though

#

I have a sneaking suspicion I know the reason why it was working on mine

#

I already had a valid data entry on mongodb

sick birch
#

That is?

dense flower
#

and it seems like for some reason it was ignoring it because of that

#

idk why but its working now is the important part haha

#

thank you for the help, i appreciate it ❤️

sick birch
#

yup

hushed karma
#

How would I go about making a bot that on command posts a random image from an archive that I made with a bunch of images

hushed karma
#

On my computer

bright wedge
unkempt canyonBOT
#

Thanks to discord.py, sending local files as embed images is simple. You have to create an instance of discord.File class:

# When you know the file exact path, you can pass it.
file = discord.File("/this/is/path/to/my/file.png", filename="file.png")

# When you have the file-like object, then you can pass this instead path.
with open("/this/is/path/to/my/file.png", "rb") as f:
    file = discord.File(f)

When using the file-like object, you have to open it in rb mode. Also, in this case, passing filename to it is not necessary.
Please note that filename can't contain underscores. This is a Discord limitation.

discord.Embed instances have a set_image method which can be used to set an attachment as an image:

embed = discord.Embed()
# Set other fields
embed.set_image(url="attachment://file.png")  # Filename here must be exactly same as attachment filename.

After this, you can send an embed with an attachment to Discord:

await channel.send(file=file, embed=embed)

This example uses discord.TextChannel for sending, but any instance of discord.abc.Messageable can be used for sending.

bright wedge
#

you can use random module for select a random image from your folder, and send it to a channel!

hushed karma
bright wedge
#

no

#

you need to install the 2.0 version

bright wedge
# hushed karma Like a file folder

you can try something like that:

import os
import random 

path="C:\\Users\\Desktop\\image"
files=os.listdir(path)
d=random.choice(files)
os.startfile(d)
#

there is to many ways to get the files from folder!

hushed karma
#

Alright thanks

shrewd apex
#

or the latest dev branch

bright wedge
granite plume
#

How do you add an image to an embed

shrewd apex
unkempt canyonBOT
#

set_image(*, url)```
Sets the image for the embed content.

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

yes, i'm only passing 1 url

shrewd apex
#

url='something'

granite plume
#

ohhhhh

waxen igloo
#

How would i prevent my grouped sub commands from sending the main group command whenever i mistype the sub command?

winged linden
#
async def rep(interaction: discord.Interaction, username1: discord.user):

how do I get username1 to be specified as a discord user, im using a slash command

shrewd apex
#

type hint it discord.Member

slate swan
hushed galleon
#

you can, you just have to set invoke_without_command=True in the parent decorator

winged linden
signal hedge
#

Is there a solution?

vocal snow
#

Read the first line

signal hedge
#

I have fixed it But it happened like this instead.

slate swan
#

can u show code u doin something wrong

signal hedge
#

Where do I have to fix it?

upbeat gust
#

You have them the wrong way around

signal hedge
upbeat gust
#

change it?

signal hedge
#

where to change

#

im a newbie and dont quite understand.

vocal snow
#

switch the positions of those two parameters

signal hedge
#

oh thx you

vocal snow
#

the same with the selectmenu

#

this needs to be self.interaction...

#

not self.Interaction

#

actually that makes no sense

#

you don't have self.interaction defined anywhere pithink

signal hedge
#

Thanks, I'm a newbie so I don't know much haha

vocal snow
#

this typehint should be discord.Interaction

signal hedge
#

I fixed it and it didn't work. 😵‍💫

vocal snow
signal hedge
#

what should i do

vocal snow
#

I'm guessing you wanted to do self.ctx.message.edit

signal hedge
#

like this?

#

it's confusing for me

vocal snow
#

instead of self.interaction.edit_original_response

vocal snow
signal hedge
#

I fixed it and it didn't work.

#

😕

vocal snow
signal hedge
#

here

vocal snow
# signal hedge

where are you defining self.message? I don't see it in the docs

signal hedge
#

Can you take a look at my code, it might be easier.

slate swan
#

you need to pass message

signal hedge
#

i don't understand it

slate swan
#

also if u check dpy discord. you will find examples

class MyView(discord.ui.View):
    def __init__(self, timeout):
        super().__init__(timeout=timeout)
        self.response = None # Define a variable named response with the initial value set to None

    async def on_timeout(self):
        for child in self.children: # We need to iterate over all the buttons/selects in the View (self.children returns a list of all the Items in the View)
            child.disabled = True   # And set disabled = True to disable them
        await self.response.edit(view=self) # Now we just need to update our old message with the updated buttons

@bot.command()
async def foo(ctx):
    my_view = MyView(timeout=30.0) # We need to create an instance of this class first, so that we can set the response to the returned message object
    out = await ctx.send('on_timeout Example', view=my_view)
    my_view.response = out # Here we're setting our `self.response` as the output message we got in return from .send()
#

if you dont understand i suggest taking a step back from discord bots and properly learning python

signal hedge
#

it's so hard

unkempt canyonBOT
meager chasm
#

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

meager chasm
#

U can see places to.learn python for free there

signal hedge
#

thx u

signal hedge
#

What do I have to change

glad cradle
signal hedge
meager chasm
#

what is self.message

#

And self.Interaction

glad cradle
# signal hedge
  1. this part of code was not present in the copypaste link

  2. you don't have an interaction attribute defined in the class and if you have defined it later than the copypaste link you should named it like interaction, interaction with the upper i indicates a class (the Interaction class), instead interaction is an Interaction object

signal hedge
#

I don't understand, I deleted the file.

#

thank you all

slate swan
#
@bot.command()
@commands.cooldown(1, 5, commands.BucketType.user)
async def test(ctx):
    await ctx.channel.send("command output")
@test.error
async def info_error(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
        await ctx.channel.send('there is a cooldown')```
#

I want the bot to tell how much time left for the cooldown

tepid flume
#

Anyone learning python from scratch?

shrewd apex
tepid flume
#

@shrewd apex how's it man.

slate swan
shrewd apex
#

learning a language is easy mastering it is tough

slate swan
#

^

#

@slate swan

await ctx.channel.send(f"Try again in {error.retry_after:.2f}s.")
#

try this

ocean dragon
#
    @commands.dynamic_cooldown(cooldown_callback, commands.BucketType.member)
    @app_commands.command(name="ping", description="Ping pong")
    @app_commands.describe(hidden="Show message as hidden")
    async def ping(self, interaction: discord.Interaction, hidden:bool=False) -> None:
        author = interaction.message.author

how come message is NoneType here?

main moth
#

Python discord bot from another script address?
Hey, I have a Discord Bot, but it can't really do much at the moment, but I want to change that now. I want the bot to write a DM to a certain user with an ID, which comes from another script (Could be PHP or python, what you find better). So script 1 does a task, gets returned so to speak a Discord name/tag. An ID and to this name a DM with the respective ID should be written. Has who possibly an example code for me?

slate swan
#

where can i go to host my discord bot 24/7

slate swan
slate swan
slate swan
#

do i just paste all my code into the vps

slate swan
#

just do research also stuff on youtube for hosting discord bots using it

main moth
slate swan
sweet pilot
#

used bot.start()

#

does discordpy prohbit commands.command in v2.0?

#

cz commands are not getting picked up

slate swan
slate swan
#

what does this mean

vocal snow
#

The key doesnt exist in the dictionary

slate swan
#

im trying to keep my bot alive by adding a background task

#

status = cycle(['with Python','JetHub'])

@bot.event
async def on_ready():
change_status.start()
print("Your bot is ready")

@tasks.loop(seconds=10)
async def change_status():
await bot.change_presence(activity=discord.Game(next(status)))

#

but it says cycle is not defined, anyone know why?

naive briar
#

Import it

slate swan
#

How do I fix?

slate swan
slate swan
slate swan
#

@slate swan your suppose to use run function not login

#

I'm guessing you are a js dev lol

#

yes

slate swan
slate swan
#

bot.run

slate swan
teal glade
#

How do you make a persistent UI button (one that still works after bot restart)

slate swan
#

Client is if you had variable saved as client and not bot

slate swan
#

import cycle?

vale wing
unkempt canyonBOT
#

add_view(view, *, message_id=None)```
Registers a [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View") for persistent listening.

This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.

New in version 2.0.
slate swan
slate swan
#

did you remove the ?

#

now it shows that

#

@slate swan dm me

slate swan
slate swan
# slate swan

This is due to you using repl, repl uses shares IPs, and there for when other people abuse the api on repl you suffer to

teal glade
slate swan
#

Do kill 1 in the console thing on repl

#

Repl is highly highly not recommend for hosting bots

slate swan
#

And I saw your bot token is public which is also a risk

slate swan
#

anyone know how to keep bot alive 24/7 on replit

#

uptimerobot

slate swan
#

did you do keep_alive.py

slate swan
slate swan
# slate swan did you do keep_alive.py

i did this:

from threading import Thread

app = Flask('')

@app.route('/')
def main():
return "Your Bot Is Ready"

def run():
app.run(host="0.0.0.0", port=8000)

def keep_alive():
server = Thread(target=run)
server.start()

#

Also I'll keep repeating this argument repl isn't for hot hosting

slate swan
slate swan
slate swan
slate swan
slate swan
slate swan
#

noooo

#

add a file called keep_alive.py

#

and put this in there

from flask import Flask
from threading import Thread

app = Flask('')

@app.route('/')
def home():
    return "Bot Online"

def run():
  app.run(host='0.0.0.0',port=8080)

def keep_alive():
    t = Thread(target=run)
    t.start()
#

at the top of your code put
from keep_alive import keep_alive

#

ok thanks

#

then above your client.run or bot.run do
keep_alive()

main moth
#

How to turn off, that discord bot does react to direct message

slate swan
slate swan
#

like that?

#

oh wait

#

keep_alive]

#

keep_alive()

main moth
slate swan
#

there

#

@main moth why are you doing that?

main moth
slate swan
#

My fault

#
if not message.guild:
  return
else:
  await client.process_commands(message)
slate swan
#

yea

#

I don't use discord py very often I mainly use nextcord

#

As I don't really trust the devs not to drop the project again

#
    activity = random.choice(random_activity)
    await client.change_presence(activity=discord.Game(name=activity))
#

ppl still dont know you can do random statuses...

slate swan
#

I feel like random should be built in function like js

#

eh

#
{"1031053618008301588": {"money": 1468, "bank": 5000, "totalmny": 1673}, "994474388042813450": {"money": 1536, "bank": 5000, "totalmny": 1536}, "950652516708782120": {"money": 1331, "bank": 5000, "totalmny": 1664}, "812729257968009256": {"money": 1500, "bank": 5000, "totalmny": 1500}, "1022261701850169445": {"money": 1500, "bank": 5000, "totalmny": 1500}}
#

economy bot lol

#
{"1031053618008301588": {"silverchest": 0, "goldchest": 0, "copperchest": 0, "fishingrod": 3, "sunfish": 14, "clownfish": 0, "nametags": 16}, "950652516708782120": {"silverchest": 0, "goldchest": 0, "copperchest": 0, "fishingrod": 1, "sunfish": 11, "clownfish": 6, "nametags": 8}, "812729257968009256": {"silverchest": 0, "goldchest": 0, "copperchest": 0, "fishingrod": 0, "sunfish": 0, "clownfish": 0, "nametags": 0}}
main moth
#

Why does it not work if i type in chat !foo test:

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


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


@client.command()
async def foo(ctx, arg):
    await ctx.send(arg)
slate swan
#

I need help with someone separating my code on repl who can.

slate swan
#

@main moth

#

the command will work but what are the intents

main moth
#

intents = Intents.default()
intents.messages = True

slate swan
#

turn all 3 on

main moth
#

Okay

slate swan
#

client = commands.Bot(command_prefix="!", intents=discord.Intents.all())

#

this will work too

slate swan
main moth
#

The is the following error: AttributeError: 'Intents' object has no attribute 'message_content'

slate swan
slate swan
#

o

slate swan
#

he used mine i think

#

wtv gn

main moth
#

someone says

#

what have i to change

sweet pilot
#

does discord require you to reinvite the bot after updating intents

main moth
#

!foo test doesnt send a message

slate swan
main moth
slate swan
main moth
slate swan
#

do you still have an on_message eceny

#

*event wtf typo

main moth
#

Yes i have an on_message event

slate swan
#

change .event to .listen()

slate swan
main moth
#

client = commands.Bot(command_prefix="!", intents=discord.Intents.all())


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


@client.command()
async def foo(ctx, arg):
    await ctx.send(arg)


@client.event
async def on_message(message):
    if not message.guild:
        await message.author.send("whoops this isn't in a server this is in dms")
        return

    if message.author == client.user:
        return

    if message.content.startswith('hi'):
        await message.channel.send('Hello!')
slate swan
#

thats what happens you watch tutorials online lol

slate swan
main moth
#

but why?

slate swan
#

client = commands.Bot(command_prefix="!", intents=discord.Intents.all())


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


@client.command()
async def foo(ctx, arg):
    await ctx.send(arg)


@client.event
async def on_message(message):
    if not message.guild:
        await message.author.send("whoops this isn't in a server this is in dms")
        return

    if message.author == client.user:
        return

    if message.content.startswith('hi'):
        await message.channel.send('Hello!')
main moth
#

And it doesnt fix the foo mistake?!

slate swan
#

because an on_message event will block your commands

main moth
slate swan
#

much better than stupid old tutorials

main moth
#

Which docs should i read

#

can you send me some via dm pls

slate swan
main moth
#

🙂

slate swan
#

i have a class rn so can't really, people here will help

main moth
#

okay

slate swan
#

Copy and pasting = very bad habit

#

yes yes

dull terrace
slate swan
vale wing
#

69% of current bot "developers": lol what

slate swan
#

💀

#

How to fix?

#

The only reasonable way to copy something is if you understand the code

vale wing
#

With wrench

dull terrace
slate swan
#

Eventually we learn how to actually code

vale wing
slate swan
slate swan
slate swan
#

its ```py
from x import y

vale wing
#

Yes

slate swan
slate swan
#

O yea I'm blind I just realised

vale wing
#

In java there's no even such thing as from iirc

slate swan
slate swan
#

?tag ip

novel apexBOT
#

This is not a Modmail thread.

slate swan
#

?tag lp

novel apexBOT
#

This is not a Modmail thread.

vale wing
#

You can either ```java
import java.util.Scanner;

Or
```java
import java.util.*;```
slate swan
#

I'm stupid

vale wing
#

I forgor the package anyway

slate swan
#

Golang only has import too

slate swan
# slate swan What do I replace?

well, code has many issues
discord_slash is no longer maintained, use dpy for slash commands
what you using flask for? hosting the bot?
and replit is one of the issues itself

slate swan
# slate swan ?

lol its a RoboDanny command, the bot is not here
you'll see that often in the dpy server

vale wing
#

That's more efficient yk

slate swan
vale wing
#

Ubuntu 22.10 sucks btw

#

It broke my SSH 😩

slate swan
#

uninstalled, I'm using manjaro with i3wm rn

vale wing
# slate swan

Typically people who ask question "what to replace" when they get syntax error they are straight out from watching a youtube tutorial and retyping the whole code not understanding a thing

slate swan
vale wing
#

Well what's your python knowledge

slate swan
#

My friend gave it to me and said “make it work”

vale wing
#

That's unrelated to my question

slate swan
vale wing
#

Nice

slate swan
vale wing
#

And how were you gonna code anything

slate swan
vale wing
#

But what if he asks to send their machine 🧐

dull terrace
#

with the code carefully typed out on paper

vale wing
#

😩

slate swan
vale wing
#

Remember how we used to code on paper

#

Good old days

cerulean folio
#

Is there really not a single way to get a Guild object from a guild id, no matter if the bot is in the guild or not??

vale wing
cerulean folio
slate swan
#

bot has to share the guild

mighty pilot
cerulean folio
#

Then how does some websites fetch informations about a server they never been into?

dull terrace
slate swan
#

users authorize to show what guilds they are in. but i dont know of anything that shows information on a guild without SHARING the guild in some way

#

which if they are, olie already mentioned prob doing something against discord tos

dull terrace
#

otherwise they might have stored info from previous users from that guild i guess

main moth
#
    if not ctx.guild:
        await ctx.author.send("whoops this isn't in a server this is in dms")
        return

    if ctx.author == client.user:
        return

I do this on every command and on_messge. Should I do it in a different async function and call it from every event or is there an easier way to set it as default?

cerulean folio
slate swan
#

what specifically are you referring to?

dull terrace
#

i have no idea what a server widget is?

cerulean folio
#

I don't mean to get critical informations about a server, just the name and the pfp

dull terrace
#

unless they mean they have a bot in the server

cerulean folio
#

this one

feral frost
#

guys how can i make it so my buttons are under each other instead of next to each other

slate swan
cerulean folio
mighty pilot
dull terrace
feral frost
cerulean folio
#

okay i'll check if the widget thingie can be implemented

mighty pilot
#

With row= 1 in your button arguments

dull terrace
#

unless you need servers that are not listed publicly

feral frost
#

ok

slate swan
mighty pilot
#

I know sites like top.gg you have to invite their bot to your server

slate swan
#

yup

#

this is a widget btw, which if the server has it enabled, its pretty simple to get the data.

feral frost
#

is there a way to store button clicks ? for example a button called 1 and another called + to like make it do 1 + 1

dull terrace
feral frost
#

how do i store the clicks ?

feral frost
dull terrace
#

depends on use case though

slate swan
feral frost
slate swan
#

just overall clicks

dull terrace
#

do you know how to make a button?

feral frost
#

yes

dull terrace
#

and you defined a custom id for it?

feral frost
#

not yet

robust fulcrum
slate swan
feral frost
#

that id good ?

dull terrace
feral frost
#

yes

mighty pilot
#

Chill there's like 9 people in here trying to get help lol

slate swan
#

idk what u even mean by this?

#

are u trying to use a discord bot to send stuff to a cmd prompt??????

mighty pilot
#

He wants a discord interaction to be able to open a new cmd tab on his PC to perform functions

dull terrace
#

and use that in the new buttons custom id

feral frost
slate swan
#

run it in an asynio task

cerulean folio
#

That's what i just figured out

#

It's exactly what I was looking for :D

#

tyyyyy

slate swan
#

!d asyncio.create_task

unkempt canyonBOT
#

asyncio.create_task(coro, *, name=None, context=None)```
Wrap the *coro* [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine) into a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task") and schedule its execution. Return the Task object.

If *name* is not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.set_name "asyncio.Task.set_name").

An optional keyword-only *context* argument allows specifying a custom [`contextvars.Context`](https://docs.python.org/3/library/contextvars.html#contextvars.Context "contextvars.Context") for the *coro* to run in. The current context copy is created when no *context* is provided.

The task is executed in the loop returned by [`get_running_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop "asyncio.get_running_loop"), [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError "RuntimeError") is raised if there is no running loop in current thread.

Note

[`asyncio.TaskGroup.create_task()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.TaskGroup.create_task "asyncio.TaskGroup.create_task") is a newer alternative that allows for convenient waiting for a group of related tasks.
slate swan
#

the only issue is that the code won't wait for it to complete

mighty pilot
cerulean folio
#

no, from their widget

mighty pilot
#

Oh if they have it enabled. I see

cerulean folio
#

It's disabled by default so i'll try to find another way

slate swan
#

yeee i actually had no clue about it until just now lol

dull terrace
slate swan
cerulean folio
slate swan
cerulean folio
#

i do know

#

but I'm looking to get these infos from a server id, without being inside it

#

like you'd find all these infos about a user even tho you're not friends and don't share any server

#

i can't believe those infos are kept so secret

slate swan
#

i think it's mostly because of their implementations of other features that make the guilds "public"

slate swan
slate swan
#

no you can't lmfao

#

unless you would like to be banned by discord

#

its becuase its a public server lmao

cerulean folio
slate swan
#

and they have discovery enabled

slate swan
slate swan
cerulean folio
#

if you aren't on the server or don't have an valid invite link, you can't get them ^^

slate swan
cerulean folio
#

thing is that I can't get invite links for servers from the id

#

you need perms to create an invite link

#

so for public servers it's possible, for small server it's nearly impossible

slate swan
#

yea technically all servers are considered "private" unless they enable discovery

slate swan
vale wing
#

And you don't do that with dpy

cerulean folio
slate swan
vale wing
cerulean folio
vale wing
#

You can code it by yourself but not with dpy

#

That's just requests stuff

cerulean folio
#

yeah I get you

vale wing
#

Depending on your application you want to use requests or aiohttp

cerulean folio
#

so that can allow me to get all the guilds from a user object without the bot being inside them?

vale wing
#

You will get access to this endpoint once user authorises using oauth2

cerulean folio
#

I see

#

I'll try to implement this, it sounds like a good thing

#

thank a lot jammy jumpKaiyo

slate swan
#

there's discord-ext-ipc for that iirc

vale wing
#

It's easy enough to done with requests imo

golden hamlet
#

is dpy still a thing

#

i heard it got discontinued

past walrus
ocean dragon
#

NotFound: 404 Not Found (error code: 10062): Unknown interaction why do I randomly get this

#

I read that u have to somehow send a response to discord that you received the command and then handle it but

naive briar
#

You took too long to respond to the interaction

#

!d discord.InteractionResponse.defer - If it needs to take more than 3 seconds, you have to defer it

unkempt canyonBOT
#

await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Defers the interaction response.

This is typically used when the interaction is acknowledged and a secondary action will be done later.

This is only supported with the following interaction types...
ocean dragon
#

that's what I found but I didnt get type hinting for that 🤔

slate swan
shrewd apex
slate swan
#

how does user inputs work on discord py

sweet pilot
#

does anyone know why discordpy doesn't show errors anymore

#

it seems like they r suppressed

slate swan
slate swan
#

can someone help me

naive briar
mighty yarrow
vocal snow
slate swan
#
@client.command()
async def shard (ctx):
  await ctx.send(embed=em)
  em = discord.Embed(
         title=f"shards")
description = """A shard is formed from a dead elemental gem,so if a lightning gem is the one that died, you'd get a lightning shard,make sure to read the info on shards in the wiki to understand better
But what you need to know is below 

Grades and prices
Grade 1(x5 boost):2 diamonds
Grade 2(x7 boost):3 diamonds
Grade 3(10x boost):5 diamonds"""  
em.set_thumbnail(url ="a gif url")```
It tells me em is not defined idk why
vocal snow
#

It's not in the function?

slate swan
#

how is it not?

#

I specified what em was

vocal snow
mighty yarrow
#

@client.command(pass_context=True)
async def unban(ctx):
banned_users = await ctx.guild.bans()

member_name, member_discriminator = member.split('#')
for ban_entry in banned_users:
    user = ban_entry.user
    
    if (user.name, user.discriminator) == (member_name, member_discriminator):
         await ctx.guild.unban(user)
         await ctx.channel.send(f"Unbanned: {user.mention}")
vocal snow
# vocal snow

On mobile atleast it looks as if em is being defined in the function locally

#

And you're trying to access it outside the function

slate swan
vocal snow
mighty yarrow
#

@client.command(pass_context=True)
async def unban(ctx, *, member):
banned_users = await ctx.guild.bans()

member_name, member_discriminator = member.split('#')
for ban_entry in banned_users:
    user = ban_entry.user
    
    if (user.name, user.discriminator) == (member_name, member_discriminator):
         await ctx.guild.unban(user)
         await ctx.channel.send(f"Unbanned: {user.mention}")
#

doesnt work also

vocal snow
#

Do you get an error? If not, are you sure the for loop and if statement are running properly?

#

And have you considered unbanning by user id instead of by name and discriminator? Would be much faster

slate swan
#

lucas tutorial moment

#

Is your unban command looking like this?

      for ban_entry in banned_users:
          user = ban_entry.banned_users

          if (user.name, user.discriminator) == (member_name, member_discriminator):
              ...

Lucas' unban only works for banning people via their name#discrim, now, this way is not wrong, but there are easier ways of unbanning people, e.g.:

# Unbanning by ID only (converting the ID to a object using discord.Object):
await ctx.guild.unban(discord.Object(id = id))

# converting the given user to a User object by type hinting:
async def unbean(ctx, user : discord.User, reason = None): 

Inspiration from d.py official server

mighty yarrow
#

but how do i get all banned members in list

slate swan
#

why do you need that huh?

mighty yarrow
#

not using disocrd id bruh

slate swan
slate swan
slate swan
slate swan
mighty yarrow
#

for member in ban_list:

#

@slate swan this??

slate swan
slate swan
slate swan
mighty yarrow
#

@slate swan

radiant parrot
#

how would i remove the title from an embed and then resend the embed with a new title?

naive briar
#

Change the embed's title property

radiant parrot
paper sluice
slate swan
#

i forgot it was a method that returns the iterator lol

mighty yarrow
slate swan
mighty yarrow
# slate swan show code

@client.command(pass_context=True)
async def unban(ctx):
await ctx.message.delete()
for member in ctx.guild.bans():
try:
await member.unban()
except:
pass

naive briar
# mighty yarrow

!d discord.Guild.bans - it's an async generator, so, use async for instead of for

unkempt canyonBOT
#

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

You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "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...
naive briar
#

Or iterator if you will

mighty yarrow
slate swan
#

what do you think

#

2 people and the docs will lie?

#

can someone give me a example of you writing a number, the bot multiplies that number and show it in a embed?

vocal snow
#

you want to take the number with on_message, a command or

slate swan
#

on message

vocal snow
#

ok, so just convert message.content to an integer with int(), multiply it and send it with message.channel.send

mighty yarrow
#

@vocal snow

#

is there a way to create channel with specific amount?

vocal snow
#

a specific amount?

mighty yarrow
#

yes

vocal snow
#

like a specific number of channels?

mighty yarrow
#

yes

vocal snow
#

use a for loop?

slate swan
#

can you help me first with

mighty yarrow
#

for i in range?

vocal snow
#

sure

slate swan
#

how do i make the bot save my message

#

like ask a question, than save the answer

vocal snow
#

where do you want to save the answer?

#

a simple bot which does what?

slate swan
#

save the asnwer so i can put it in a embed

vocal snow
slate swan
#

well it asks this, however how do i make it wait for them to type something and it comes up in a embed @vocal snow

vocal snow
#

!d discord.Client.wait_for

unkempt canyonBOT
#

wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.11)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.11)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.11)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
vocal snow
#

there are examples in the doc

vocal snow
#

what?

slate swan
#

@bot listen

vocal snow
#

I really have no idea what you mean

slate swan
#

im stuck at this for days

vocal snow
# unkempt canyon

I'm just saying that if you want to wait for an on_message event to get a user's message inline you use this

slate swan
vocal snow
#

umm im not sure why you sent this

slate swan
#

DUDE

#

wait_for(event, /, *, check=None, timeout=None)

#

how does this work

vocal snow
#

there is a detailed description as well as examples in the doc