#discord-bots

1 messages ยท Page 273 of 1

ember mango
#

I have one question?

#

Discord.js = JavaScript?
And is it true that it does not require a database?@slate swan

vocal snow
#

what

slate swan
ember mango
slate swan
ember mango
#

@vocal snow
I am mobile

#

I can't download app datebase

#

Because i want to use js

buoyant quail
#

If you want then use

ember mango
buoyant quail
#

No one is stopping you

vocal snow
#

databases are independent of the programming language

#

and you can use a file based one like sqlite

slate swan
ember mango
#

On python

buoyant quail
#

sqlite database is a single file without anything

ember mango
#

That is, it will be mobile without
download the app datebase?

#

I mean mobile

buoyant quail
#

I believe mobiles can create and write into files

ember mango
ember mango
#

You True?

#

๐Ÿ—ฟ

#

Anyway ty

left dew
#

hi so im splitting a list e.g. [100, harvesters, 100, icepiercers] and making it print like

x100 Icepiercers```

however the number and item wont print on the same line in the code below

```py
          values = c.split(",")
          formatted_string = ', '.join(values)

formatted_string1 = re.sub(r'(\d+)', r'x\1 ', formatted_string)

formatted_string2 = formatted_string1.replace(', ', '\n')
          formatted_string3 = formatted_string2.title()
          formatted_string4 = formatted_string3.replace(' X ', ' x ')```
left dew
#

oh ok

buoyant quail
#

Working with list โŒ
Working with it's representation and regex incident_actioned

slate swan
left dew
#

how would i get the embeds field value that a button is attached to when a button is clicked

shrewd apex
#

u would have to edit the embed in the button callback

harsh orbit
#
import discord
import os
from discord.ext import commands
from discord import member
from discord.ext.commands import has_permissions, MissingPermissions

intents= discord.Intents.all()

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

Token = os.environ['token']

@bot.event
async def on_ready():
  print("Bot Online")

@bot.event
async def on_member_join(member):
  join_channel_id = 1028256485383344170
  join_channel = bot.get_channel(join_channel_id)
  member = str(member.mention)
  await join_channel.send(member + " is here")

@bot.event
async def on_member_remove(member):
  leave_channel_id = 1028256485383344170
  leave_channel = bot.get_channel(leave_channel_id)
  member = str(member.mention)
  await leave_channel.send('GoodBuy ' + member)


@bot.command(pass_contaxt = True)
async def joinme(ctx):
 if (ctx.author.voice):
   voice_channel = ctx.message.author.voice.channel
   await voice_channel.connect()
   await ctx.send("Ok")

 else:
   await ctx.send("You aren't in voice channel")

@bot.command(pass_contaxt = True)
async def leave(ctx):
  if (ctx.voice_client):
    await ctx.guild.voice_client.disconnect()
    await ctx.send("I left the voice channel")

  else:
      await ctx.send("I'm not in voice channel")

@bot.event
async def on_message(message):
 if message.content == "ูƒุณู…ูƒ":
   await message.delete()
   await message.channel.send("ูƒุณุฎุชูƒ")
   
@bot.command()
@has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, reason=None):
  await member.kick(reason=reason)
  await ctx.send(f"{member.mention} Has kicked")

@kick.error
async def kick_error(ctx, error):
  if isinstance(error, commands.MissingPermissions):
    await ctx.send("You don't have permissions to kick memebrs")



bot.run(Token)

Why kick command not working

#

@slate swan

slate swan
#

yo, does anyone know how oauth works for discord and can explain simply to me lol, the docs really confuse me. all i want to do is make one of those bots like restorecord that use discord oauth to "verify" users in a discord server

slate swan
#

def handle_place(place: str) -> tuple[str, str]:
    places = response_json()['search_place_responses']
    place_data = places.get(place)
    if place_data is None:
        return None, None

    get_choice = random.choice(place_data)
    messages = get_choice.get("messages")
    item_probs = get_choice.get("gained", {})

    if messages is not None:
        sentence = random.choice(messages)
    else:
        sentence = None

    if item_probs:
        items = list(item_probs.keys())
        probabilities = list(item_probs.values())
        rand_item = random.choices(items, probabilities)[0]
        return sentence.format(str(rand_item)), rand_item, "item"

    if (coins_minmax := get_choice.get("coins")) is not None:
        coins_gained = random.randint(*coins_minmax)
        return sentence.format(str(Config().currencyEmoji), str(coins_gained)), str(coins_gained), "coin"

    return sentence, None, None
``` this is my function for the search command, and my json structure looks something like this
```json
"search_place_responses": {
        "Hospital": [
            {
                "messages": [
                    "You found yourself walking on top of needles, you fell to the floor and woke up years later"]
            },
            {
                "messages": [
                    "You lift up a patient in a coma, but suddenly he wakes up and gives you a **{}**",
                    "The nice nurse gave you a **{}**"
                ],
                "gained": {
                    "Silverware": 0.25
                }
            },
            {
                "messages": [
                    "You found **{} {}** ..."
                ],
                "coins": [200, 250]
            }
        ],}``` i was curious as to how can i make the chance of receiving the items smaller as in you would get coins more often than items since if theres just 1 item in the gained then the chance would be 100% for it, how can i make it a little smaller?
upbeat ice
#

Do you think this is appropriate? I am timing out the view and editing the view to none, but there are cases where if the cmd is called from a channel the bot does not have access to it will fail to edit. ```py
async def on_timeout(self):
try:
await self.interaction.message.edit(view=None)

    except discord.HTTPException as e:
        # We are unable to edit the message - most likely the command was called in a channel the bot can't see
        pass
    super().stop()```
naive briar
#

It will not be able to receive the command in the first place

upbeat ice
#

is that true for app commands?

#

Because I can call the command in a channel the bot can't see

turbid condor
glossy oar
#

@cerulean ibex bro y u blocked me?

#

lwde

slate swan
#

hi, does anyone know why this button is not changing colour?

@bot.command()
async def sendverify(ctx, channelid):
    channel = bot.get_channel(int(channelid))
    button = Button(label="Verify", style=discord.ButtonStyle.green)
    view = View()
    view.add_item(button)
    await channel.send("Click the button below to verify", view=view)
#

its like this:

slate swan
#

i mean it has a url on it but I couldn't really share it

sick birch
#

If you save and re-run the bot and run the command again, the URL will go away

slate swan
#
@bot.command()
async def sendverify(ctx, channelid):
    channel = bot.get_channel(int(channelid))
    button = Button(label="Verify", style=discord.ButtonStyle.green, url="https://example.com")
    view = View()
    view.add_item(button)
    await channel.send("Click the button below to verify", view=view)
#

no but like i need the url lol

sick birch
#

I don't know if you can make colors on URL buttons

slate swan
#

if it has a url it will be gray

#

oh fine

#

okay

slate swan
sick birch
#

You can't do that with link buttons either

slate swan
#

oh damn lmao

sick birch
#

Link buttons are very restrictive in that they're just UI components, they just act as fancy hyperlinks

unkempt canyonBOT
#

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

Waits until the view has finished interacting.

A view is considered finished when [`stop()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.stop "discord.ui.View.stop") is called or it times out.
sick birch
#

They don't have callbacks or events or colors or anything like that

slate swan
#

its like for verifying people

#

and like i swear ive seen something

#

doesnt matter what link it is

sick birch
#

Then you can detect it when they get redirected back to your webserver with the authorization code grant

slate swan
#

you just cant have a callback on such button

sick birch
#

Exchange the auth code for access token as usual, you know the drill
use the access token to get the user's information, match that up to see if it's who ran the command

#

easier said than done of course

slate swan
#

but would the bot and the server not have to be running on the same file or pc even?

#

no why would it

sick birch
#

not necessarily

#

you will have to set up some sort of IPC pipeline though

slate swan
#

you can set redirect url to anything

#

so it can redirect to other server

sick birch
#

technically you could use aiohttp to set up a web server

#

but eh

dense mesa
#

Hello all. Im in a bit of a pickle. I've tried setting up my first Discord bot with integrated GPT 3.5 response for somewhat more convenient communication between me and OpenAI.

Everytime i run the code, it works for when i message the bot directly with the command, but when i use it in a text channel in my Discord server it doesnt respond.

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.

sick birch
#

You're probably missing message_content intent

dense mesa
#

๐Ÿ˜ญ

#

It had that line of code,and like i said lol... It worked via DM but when the command in a channel that was use in my server where my bot is it didn't respond

sick birch
#

Do you have it enabled in the developer dashboard as well?

dense mesa
#

Yeah lol ... My bot is actually administrator privileges

obsidian pagoda
#

Hi, Iโ€™m looking for a team to make a discord bot with me, itโ€™s no paid for, Iโ€™m looking for 5-6 members in the team:)

void pumice
#

I want to create discord crypto wallet bot but idk which api I can use for crypto Transaction 2019mochasit
Can anyone help me to create that type of bot ?

upbeat gust
void pumice
void pumice
upbeat gust
#

Like why would people let you access their crypto wallets and money?

#

I dont think you've thought this through

void pumice
upbeat gust
void pumice
copper gulch
#
    @commands.command()
    async def buttons(self, ctx):
        msg_with_buttons = await ctx.send('Hey here are some Buttons', components=[[
        Button(label="Hey i\'m a red Button",
            custom_id="red",
            style=ButtonStyle.red),
        Button(label="Hey i\'m a green Button",
            custom_id="green",
            style=ButtonStyle.green),
        Button(label="Hey i\'m a blue Button",
            custom_id="blue",
            style=ButtonStyle.blurple),
        Button(label="Hey i\'m a grey Button",
            custom_id="grey",
            style=ButtonStyle.grey)
]])

        def check_button(i: discord.Interaction, button):
            return i.author == ctx.author and i.message == msg_with_buttons
    
        interaction, button = await self.client.wait_for('button_click', check=check_button)
    
        embed = discord.Embed(title='You pressed an Button',
        description=f'You pressed a {button.custom_id} button.',
        color=discord.Color.random())
        await interaction.respond(embed=embed)

can someone help me with buttons, I dont understand every docs I read

#
error:
 raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Button.__init__() got an unexpected keyword argument 'custom_id'
hasty pike
hasty pike
copper gulch
#

yea but I decided to change to pycord

#

but I dont know if it will work with my slash commands

hasty pike
#

๐Ÿคก

#

Better read docs

#

Discord components no longer works

#

You need discord view

#

Against Tos

void pumice
faint wasp
#

I was just trying to store msg in a txt file from an active server

hasty pike
faint wasp
#

cuz I can't make my bot get added in active server

#

I want to store 100k msg from a server in txt file

copper gulch
faint wasp
#

alright ty

naive briar
#

What education purposes would you get from selfbotting

#

!rule 5

unkempt canyonBOT
#

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

hasty pike
copper gulch
#

eh?

hasty pike
void pumice
copper gulch
hasty pike
copper gulch
#

THANK YOUU ๐Ÿ˜ญ

hasty pike
#

This is the Ultimate Python Guide on Buttons with Discord.py or Pycord. In this video, I talk about how to create buttons in discord.py or pycord and how to respond to button clicks along with everything about Views. After watching this you'll know everything about Buttons and Views in discord.py or pycord.

This video might also apply to other...

โ–ถ Play video
void pumice
hasty pike
#

For different methods and better understanding

copper gulch
hasty pike
copper gulch
#

Ill just save it in my bookmark. thanks you so muchh btw

hasty pike
void pumice
hasty pike
void pumice
naive briar
hasty pike
naive briar
#

For one thing, order of item callback arguments are not the same in discord.py

#

In discord.py's item callback arguments have the interaction comes before the item

hasty pike
#

It's just about arguments you could change that

naive briar
#

You could not change what arguments it gives

#

At least not without modifying how the view dispatch the items

hasty pike
#

Well i never had any issue in migrating

buoyant quail
#

define isn't working

#

i see

#

channel doesn't have send_message method

#

and you didn't gave any arguments there anyways

#

oh

#

it's not even channel by you

#

it is an integer

#
await 5.send_message()

brainmon

hasty pike
slate swan
#

๐Ÿค”

buoyant quail
#

It's different code

#

And now it'd work i guess

slate swan
#

Whatโ€™s his problem?

buoyant quail
#

ah

#

you redefined message

#

to a string

#
@client.event
async def on_message(message): # << here it is a message object
  if message.author == client.user: # and here
            return # and here
  await client.process_commands(message) # and here
  message = message.content.lower() # now it is a string
  print(message.channel.id) # string has no attribute channel
  if "hello" in message:
    await message.channel.send('hi')
slate swan
#

Ahh

hasty pike
#

Ahh

#

My bad

#

Didn't notice

copper gulch
#
class helpslash(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    class View(View):
        @discord.ui.button(label = "Click me", style = discord.ButtonStyle.green, emoji="๐Ÿ˜Ž", custom_id="Button1")
        async def button_callback(self, button, interaction):
            await interaction.response.edit_message("clicked", view = View())
        
    @app_commands.command(name="button")
    async def button(self, ctx:discord.Interaction):
    
        await ctx.response.send_message("This is a test button", view = View())

I need help with this cog, it's sending the message but it's not showing the button

#

it's a slash command aswell

turbid condor
#

Try moving you view out of the cog

copper gulch
#

ok ok

slate swan
copper gulch
#

but its fine, this is part my first time learning experience xd

#

class MyView(discord.ui.View):
    @discord.ui.button(label = "Click me", style = discord.ButtonStyle.green, emoji="๐Ÿ˜Ž")
    async def button_callback(self, button, interaction):
        await interaction.response.edit_message("clicked")
    

class helpslash(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    
    @app_commands.command(name="button")
    async def button(self, ctx:discord.Interaction):

        await ctx.response.send_message("This is a test button", view = MyView())

ok Im so confused rn, how do I make the button edit the message "this is a test button"

#

it keeps sayng

await interaction.response.edit_message("clicked")

this is the problem

buoyant quail
unkempt canyonBOT
#

examples/views/counter.py line 28

async def count(self, interaction: discord.Interaction, button: discord.ui.Button):```
copper gulch
#

wait lemme rerun

copper gulch
copper gulch
slate swan
hasty pike
#

Ctx: discord.Interaction???

#

Weird

copper gulch
#

oh right

hasty pike
#

Makes sense tho ๐Ÿ˜‚

buoyant quail
#

interaction: comamnds.Context :p

copper gulch
#

and got it, tis solved

copper gulch
copper gulch
slate swan
#

good luck understanding what it does after

#

confusing names

hasty pike
copper gulch
#

class MyView(discord.ui.View):
    @discord.ui.button(label = "Click me", style = discord.ButtonStyle.green, emoji="๐Ÿ˜Ž")
    async def button_callback(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.edit_message("clicked")
    

class helpslash(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    
    @app_commands.command(name="button")
    async def button(self, interactions:discord.Interaction):

        await interactions.response.send_message("This is a test button", view = MyView())
#
TypeError: InteractionResponse.edit_message() takes 1 positional argument but 2 were given
#

Im so confused rn...

#

nvm, I dont got it

#

anddd I got it

#

forgot the content = thingy

naive briar
#

!e

class A:
    def a(self, *, b):
        print(b)

A().a(0)
unkempt canyonBOT
#

@naive briar :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 5, in <module>
003 |     A().a(0)
004 | TypeError: A.a() takes 1 positional argument but 2 were given
heady creek
#

question. im using interactions and discord.ext. i keep trying to get the history of a channel, so i do ctx.channel.history() and i get the error AttributeError: 'Channel' object has no attribute 'history

if i go into the docs, it says that "history" is a method, but i can NOT for the life of me get it to work anywhere. Anyone see what im doing wrong?

heres the code right now:

@client.command(
    name="ping",
    description='Test Command',
    scope=servers
)
async def _ping(ctx: interactions.CommandContext):
    user_id = ctx.author.id
    hist = ctx.channel.history()
    await ctx.send("OK!")
naive briar
#

What library are you using

slate swan
naive briar
#

Well, are you using a third-party library to make slash commands

#

My bad, didn't read the full message

#

!d discord.TextChannel.history

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the destinationโ€™s message history.

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.

Examples

Usage...
buoyant quail
slate swan
heady creek
naive briar
#

Ik

slate swan
#

its interactions and their docs are

#

how to say it i cant find useful info here

naive briar
buoyant quail
#

I'd guess it's ChannelHistory method

#

but it's a weird naming for python

naive briar
#

PascalCase ๐Ÿ™€๐Ÿ™€๐Ÿ™€

buoyant quail
#

and their docs are very hard to read comparing to dpy

buoyant quail
#

i am not sure there

slate swan
glad cradle
hasty pike
#

'User' object has no attribute roles

#
async def role(ctx, user:discord.User, role:discord.Role):
  if role not in user.roles:
      await user.add_roles(role, reason=f"Given Role by {ctx.author}")
      await ctx.send(discord.Embed(description=f'Added {role.mention} to your roles.'))
buoyant quail
#

!d discord.User

unkempt canyonBOT
#

class discord.User```
Represents a Discord user.

x == y Checks if two users are equal.

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

hash(x) Return the userโ€™s hash.

str(x) Returns the userโ€™s handle (e.g. `name` or `name#discriminator`).
buoyant quail
#

because it doesn't have it

hasty pike
#

!d discord.Member

unkempt canyonBOT
#

class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").

This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").

x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.

x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.

hash(x) Returns the memberโ€™s hash.

str(x) Returns the memberโ€™s handle (e.g. `name` or `name#discriminator`).
buoyant quail
#

Member has
User not

hasty pike
#

I didn't know it's different

#

Sorry

buoyant quail
#

If they were the same on of them would be useless ยฏ_(ใƒ„)_/ยฏ

plucky knoll
#

Does max_concurrency decorator not work for app_commands?

plucky knoll
#

So I have to create a set of guild ids..

#

Thank you

dusk pumice
#

How can I do

async def on_message(msg):

in cogs?

slate swan
#

!d discord.ext.commands.Cog.listener

dusk pumice
#

I tried this

@commands.Cog.listener()
    async def on_message(self, msg):

but didn't worked

unkempt canyonBOT
#

classmethod listener(name=...)```
A decorator that marks a function as a listener.

This is the cog equivalent of [`Bot.listen()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen").
dusk pumice
#

My program couldn't load cogs

#

lol

slate swan
#

if cog is not loaded obviously commands and events inside are not too

lost cliff
#

HELP MW

slate swan
#

what does it do so it makes so many requests

lost cliff
night crater
#

i'm pretty sure you just got cloudflare banned so you must have been sending an awful lot of requests or sending a lot of messages with big payloads

lost cliff
#

the code is huge

slate swan
#

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

lost cliff
#

idk actually

#

I have no idea how rate limits work

night crater
#

I mean to get CF banned with just messages you need to be shipping a lot of data really

#

or just a really high number of requests

lost cliff
#

OHHH

#

I Think I know now

night crater
#

oh?

lost cliff
#

it scans every message on the server

#

to check for some words

#

and the chats are pretty active especially minecraft chat

night crater
#

your code desperately needs a code formatter run over it btw...

#

I really recommend installing black

#

and just formatting everything

lost cliff
#

or an app

slate swan
#

python module

#

!pypi black

unkempt canyonBOT
slate swan
#

you install it then you have black command

#

you run it and specify path to files and it formats them

lost cliff
lost cliff
#

I think I did it

slate swan
#

yes

hushed galleon
lost cliff
#

nvm I Figured it out

#

I have 4 slots and im running a few other bots

#

they all got the same ip and all scan messages

buoyant quail
#

My eyes
๐Ÿ˜ฐ

ember mango
#

Hi can anyone help me?

buoyant quail
ember mango
buoyant quail
unkempt canyonBOT
#

str.join(iterable)```
Return a string which is the concatenation of the strings in *iterable*. A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") will be raised if there are any non-string values in *iterable*, including [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. The separator between elements is the string providing this method.
buoyant quail
#

!e

x = ["a", "b", "c"]
print(" * ".join(x))
unkempt canyonBOT
#

@buoyant quail :white_check_mark: Your 3.11 eval job has completed with return code 0.

a * b * c
buoyant quail
#

Good for free can't exist.

I can suggest render.com for example
Also i have seen in this chat dash.daki.cc

#

Wdym by doesn't work? I believe you can install any library there

ember mango
buoyant quail
#

Rand is a list of strings
Use that method on it.

buoyant quail
#

||Begin from learning python and not from making bots||
{' '.join(rand)}

buoyant quail
#

Show how it didn't work.

ember mango
buoyant quail
#

Single quotes

#

You are inside the double ones already

buoyant quail
#

Then do again.

ember mango
#

I want nothing in it

buoyant quail
#

You can put anything you want

#

Nothing will work too

#

!e

x = ["๐Ÿ˜€", "๐Ÿ˜‰", "๐Ÿ˜“"]
print("".join(x))
unkempt canyonBOT
#

@buoyant quail :white_check_mark: Your 3.11 eval job has completed with return code 0.

๐Ÿ˜€๐Ÿ˜‰๐Ÿ˜“
vale wing
tall temple
#

hi

#

please how can i customize my embed fields like that :

#

like if i want to let it be in the middle etc..

thin raft
#

play with

tall temple
thin raft
#

!d discord.Embed.add_field

unkempt canyonBOT
#

add_field(*, name, value, inline=True)```
Adds a field to the embed object.

This function returns the class instance to allow for fluent-style chaining. Can only be up to 25 fields.
thin raft
#

inline value

tall temple
#

yeah thanks

hasty pike
#

Is it possible to do reply on message.channel.send()

thin raft
#

!d discord.TextChannel.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
thin raft
hasty pike
#

In short

#

I can't

#

I needed something like ctx.reply()
But didn't find anyway to do it

thin raft
hasty pike
slate swan
#

You can

thin raft
#

you just need to pass a message object to reference

slate swan
#

You just pass reference kwarg

hasty pike
slate swan
hasty pike
slate swan
#

I dont think author have .message attrubute

#

You are supposed to do channel.send(..., reference=msg)

hasty pike
#

I'm inside on_message

naive briar
#

Find what message

slate swan
#

!d discord.on_message

unkempt canyonBOT
#

discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") is created and sent.

This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.

Warning

Your botโ€™s own messages and private messages are sent through this event. This can lead cases of โ€˜recursionโ€™ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
hasty pike
slate swan
#

Try

hasty pike
#

Should

hasty pike
slate swan
#

๐Ÿ‘

thin raft
#

I just realised

#

couldn't you just do

#

!d discord.Message.reply

unkempt canyonBOT
#

await reply(content=None, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

A shortcut method to [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message").

New in version 1.6.

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

BRUH i just defined it ๐Ÿ˜‚

thin raft
#

!d json.load

unkempt canyonBOT
#

json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)```
Deserialize *fp* (a `.read()`-supporting [text file](https://docs.python.org/3/glossary.html#term-text-file) or [binary file](https://docs.python.org/3/glossary.html#term-binary-file) containing a JSON document) to a Python object using this [conversion table](https://docs.python.org/3/library/json.html#json-to-py-table).

*object\_hook* is an optional function that will be called with the result of any object literal decoded (a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict")). The return value of *object\_hook* will be used instead of the [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict"). This feature can be used to implement custom decoders (e.g. [JSON-RPC](https://www.jsonrpc.org) class hinting).

*object\_pairs\_hook* is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of *object\_pairs\_hook* will be used instead of the [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict"). This feature can be used to implement custom decoders. If *object\_hook* is also defined, the *object\_pairs\_hook* takes priority.
thin raft
#

it needs to be a str

tall temple
#

yeah i tryed with str

#

look at this

wicked atlas
#

With load, I believe it needs to be a file object with open()

tall temple
thin raft
#

show full code

tall temple
#

my bad ur right i just check my other script and it's not the same lmfaaooooo

thin raft
#

fp stands for file path idk if you necessarily needs a stream

tall temple
#

sorry ๐Ÿ™

wicked atlas
buoyant quail
#

json.load = file object
json.loads = text

#

there is no method for just filename

#

because it's kinda useless /

wicked atlas
#

Although now Iโ€™m wondering why they chose fp as the parameter

thin raft
#

that's why I questioned it

#

wouldn't it be a stream?

#

!d open

unkempt canyonBOT
#

open(file, mode='r', buffering=- 1, encoding=None, errors=None, newline=None, closefd=True, opener=None)```
Open *file* and return a corresponding [file object](https://docs.python.org/3/glossary.html#term-file-object). If the file cannot be opened, an [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError "OSError") is raised. See [Reading and Writing Files](https://docs.python.org/3/tutorial/inputoutput.html#tut-files) for more examples of how to use this function.

*file* is a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object) giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed unless *closefd* is set to `False`.)
queen wren
#

Has discord.py any function to catch webhooks messages, instead of on_raw_message?

upbeat ice
queen wren
#

Welp, thanks ๐Ÿ™Œ

upbeat ice
queen wren
#

i was talking about on_message

upbeat ice
#

Then yes, you could do what I suggested in on_message as a simple check

hasty pike
#

role.position exists?

sick birch
unkempt canyonBOT
#

The position of the role. This number is usually positive. The bottom role has a position of 0.

Warning

Multiple roles can have the same position number. As a consequence of this, comparing via role position is prone to subtle bugs if checking for role hierarchy. The recommended and correct way to compare for roles in the hierarchy is using the comparison operators on the role objects themselves.

sick birch
#

it appears as if so

hasty pike
#
data = ([role for role in ctx.guild.roles])
data = sorted(data, key=lambda role:role.postion, reverse=True)
upbeat ice
#

you are correct

#

there is no role."postion"

buoyant quail
tall temple
#

guys how can i make slash command option like discord.Option(discord.Member) but for channels selecting like that (pycord)

buoyant quail
#

I can't be sure about pycord but just typehint it i guess

upbeat ice
buoyant quail
unkempt canyonBOT
#

examples/app_commands/slash_options.py lines 38 to 46

@option(
    "channel",
    Union[discord.TextChannel, discord.VoiceChannel],
    # You can specify allowed channel types by passing a union of them like this.
    description="Select a channel",
)
async def select_channel(
    ctx: discord.ApplicationContext,
    channel: Union[discord.TextChannel, discord.VoiceChannel],```
tall temple
buoyant quail
unkempt canyonBOT
#

examples/app_commands/slash_basic.py line 37

async def joined(ctx: discord.ApplicationContext, member: discord.Member = None):```
buoyant quail
#

you can test it

tall temple
#

okok

#

please what's the problem here ๐Ÿ™

@default_permissions(administrator = True)
@bot.slash_command(name = "ghostping", description = "Set a channel as a greeting channel")
async def ghostping(ctx, channel : discord.Option(discord.TextChannel, "Select here the channel you want to set as a greeting channel")) :
    
    if channel.id not in config['ghostping_channels_ids'] :
        ww = config['ghostping_channels_ids'].append(channel.id)
        with open("config.json", "w") as f :
            json.dump(ww, f, indent = 4)
        await ctx.respond(embed = discord.Embed(description = f"\โœ… You successfully **enabled** greeting from {channel.mention} !"), ephemeral = True)

    else :
        ww = config['ghostping_channels_ids'].pop(channel.id)
        with open("config.json", "w") as f :
            json.dump(ww, f, indent = 4)
        await ctx.respond(embed = discord.Embed(description = f"\โœ… You successfully **disabled** greeting from {channel.mention} !"))
#

when i execute the command the file content get erased ... before :

#

after :

buoyant quail
#

!e

A = [1, 2, 3]
print(A.append(4))
unkempt canyonBOT
#

@buoyant quail :white_check_mark: Your 3.11 eval job has completed with return code 0.

None
buoyant quail
#

^

#

It's in-place method

tall temple
#

mhm ?

#

i can append only str ?

buoyant quail
#

You can append anything

#

but append method returns nothing

tall temple
#

oh

tall temple
#

ohh my bad

#

i didn't have to assign it to a variable my bad

#

yeah that's it @buoyant quail thx

thin raft
tall temple
thin raft
tall temple
cunning iris
#

what's the best way to create a DB to use with my bot but also with an external API (like a REST one for example since it's the only thing I know rn)

sick birch
cunning iris
#

so if I make a REST API, I'll build everything I need in here, then have the bot make the requests ?

sick birch
#

From a certain point of view your bot is simply a "front end"

cunning iris
#

are there 'easy' ways to make bots interact with API ? I've only tackled this problem with flutter, but never with a python discord bot tbf

sick birch
#

If you have an OpenAPI spec you can generate SDK-like consumers for your API

cunning iris
#

oh great, ty ๐Ÿ™‚

slate swan
sick birch
# slate swan

Do those functions have anything except the comments?

#

Not sure if that's how it is in your code or if you cut that part out

slate swan
#

Tbh idk how to code im using chatgpt and its not as easy as i hoped

sick birch
#

Python doesn't like it when you have empty functions

#

You can put pass to indicate that it's empty, like so:

@bot.command(name='stockset')
async def set_stock(ctx, amount: str):
    pass
slate swan
#

will that fix the indented block errors

sick birch
#

!resources I would recommend going through a beginner guide as this will be covered there

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.

sick birch
#

discord.py is unfortunately not really meant for beginners

slate swan
#

Sadge

#

Ty

plucky knoll
#

@app_commands.is_owner() is not a thing? Does the library have an alternative or do I need to define a check

vocal snow
#

yeah I think you'll need to make your own

dusk pumice
#

How do I calculate timestamp in python?

#

Is there ant library?

naive briar
dusk pumice
#

Discord timestamp

naive briar
#

!d discord.utils.format_dt you mean this?

unkempt canyonBOT
#

discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)") for presentation within Discord.

This allows for a locale-independent way of presenting data using Discord specific Markdown...
dusk pumice
#

like <T:00000000> like this?

naive briar
dusk pumice
#

thanks

smoky patrol
#

Embed object has no attribute set_thumbnail

#

i can only set image

#

what can i do

naive briar
#

!d discord.Embed.set_thumbnail

unkempt canyonBOT
#

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

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

Changed in version 1.4: Passing `None` removes the thumbnail.
warm coral
#

guys i dont understand how to learn discord.py coding language

warm coral
#

wow

#

that helped alot

smoky patrol
smoky patrol
warm coral
smoky patrol
#

learning by doing

slate swan
warm coral
naive briar
#

I don't see how that's making fun of anyone

slate swan
#

You need to learn more python before touching discord.py then

warm coral
#

i know python basics

smoky patrol
smoky patrol
warm coral
#

this is too simple

smoky patrol
#

what do you know?

#

you know stuff about requests?

warm coral
#

elif if and loops

#

and other things

turbid condor
#

What about oops?

smoky patrol
warm coral
#

its very dangerous to reveal to someone

#

u dont know

smoky patrol
slate swan
#

Ideally you should be familiar with OOP and know a bit about async/await before using discord.py

turbid condor
warm coral
#

i dont understand oop too

smoky patrol
turbid condor
#

I never said it won't work i just said you will be having a hard time

smoky patrol
#

what makes it hard?

#

errors?

turbid condor
naive briar
#

If you know what instances are, then you already have some knowledge about OOP

smoky patrol
turbid condor
#

Like what have u worked on so far using that?

smoky patrol
turbid condor
#

Welp what about views?

smoky patrol
#

never heard of it tell me more

slate swan
#

components in messages

smoky patrol
#

like keywords?

slate swan
#

no like buttons dropdowns etc

turbid condor
#

And in simpler terms the buttons, drop downs etc

naive briar
#

Buttons, drop-downs, ...

warm coral
#

so i need to learn oriented object programming to begin to learn discord bot language ?

slate swan
#

there is no discord bot language?

naive briar
smoky patrol
naive briar
#

You'd just have a hard time if you don't

slate swan
smoky patrol
smoky patrol
warm coral
slate swan
smoky patrol
smoky patrol
warm coral
#

i meant python

smoky patrol
#

i used class MyView(discord.ui.View):

warm coral
#

but the discord one yk

turbid condor
turbid condor
#

And there is not one but many that u can use

slate swan
smoky patrol
turbid condor
#

For example: discord.py, py-cord, nextcord and disnake and there might be others

slate swan
turbid condor
slate swan
#

requests GIGACHAD

buoyant quail
slate swan
#

http.client

#

ws_connect meafterthesex

buoyant quail
#

C language

slate swan
#

Assembly

smoky patrol
#

golang ๐Ÿ

buoyant quail
#

Folders

smoky patrol
#

python for discord bots very easy

#

for other stuff golang better

slate swan
smoky patrol
naive briar
#

What

buoyant quail
#

I guess he means their realization in that library

slate swan
#

just looking at the example skull

smoky patrol
#

slash commands are very bad in golang

#

that is why im using python for it

slate swan
#

write your own wrapper GIGACHAD

smoky patrol
#

golang is future for the other stuff

slate swan
smoky patrol
#

@warm coral

#

what do you want to code

warm coral
#

i wanna code bots

smoky patrol
#

nice

#

that would take 1 minute

#

what features?

warm coral
#

a moderation bot

#

i dont want someone to do it for me

#

and a ticket bot

smoky patrol
#

watch videos

#

there are 1 million

warm coral
#

ok

turbid condor
slate swan
#

๐Ÿคฆ youtube videos are outdated

naive briar
#

I wonder how many of them will be using JSON

buoyant quail
slate swan
#

check the docs and examples on github if you really wanna learn something

turbid condor
smoky patrol
slate swan
naive briar
smoky patrol
buoyant quail
#

so we will say him good luck

smoky patrol
#

to understand it

warm coral
#

thanks guys for help

naive briar
turbid condor
#

How is that better?

slate swan
#

yeah its better to learn from crappy videos and then relearn from the examples since the youtube videos code doesnt work in most cases any more

smoky patrol
#

can someone help me

#

set_thumbnail aint working in my whole code anymore

vocal laurel
#

Whatโ€™s image_url?

smoky patrol
#

its a url

#

image

#

someone can help

turbid condor
smoky patrol
#

Yes

#

I printed

#

And used set_image and it works, it is nothing with the url

#

Very weird

turbid condor
#

Can you put a print statement in your if condition where you are setting the thumbnail

smoky patrol
#

The set_thumbnail isnโ€™t there as a option to put in

#

In my whole code all set_thumbnail ainโ€™t working worked 1h ago

turbid condor
#

Welp in the above ss you sent, the set_thumbnail will only be set when it satisfies the condition you set

smoky patrol
#

Okay added print

#

Printed but error

turbid condor
#

Can u show the error

smoky patrol
turbid condor
#

This is dpy right?

#

!d discord.Embed.set_thumbnail

unkempt canyonBOT
#

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

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

Changed in version 1.4: Passing `None` removes the thumbnail.
turbid condor
lost dove
#

Fr reading code in image sux

buoyant quail
#

At least not a photo from phone :\

smoky patrol
#

`@tree.command(guild=discord.Object(id=), name='websiteinfo', description='Website Info Generator')

@app_commands.describe(shoename="Shoename", link="Link", site="Website", droptime="Droptime", retail="Retail", channelid="Channel", stock="Stock", image="Image URL")
async def releaseinfo(interaction: discord.Interaction, shoename: str, link: str, site: str, droptime: str, stock: str, retail: str, channelid: str, image: str):
if interaction.user.id not in allowed_user_ids:
await interaction.response.send_message("You cant use that command", ephemeral=True)
return
else:
try:
channel = interaction.channel
embed = discord.Embed(title=shoename, url=link, color=discord.Color(0x8a77ff))
embed.description = f"Droptime: <t:{droptime}:R>\n\nSite: {site}\n\nStock: {stock}\n \nPrice: {retail}โ‚ฌ\n\n<#{channelid}>"
embed.set_thumbnail(url=image)
embed.set_footer(text='ShinyNotify โ€ข Release Info', icon_url="")
class MyView(discord.ui.View):
def init(self):
super().init()

            @discord.ui.button(label="Post", row=0, style=discord.ButtonStyle.success, emoji="โœ…")
            async def first_button_callback(self, button: discord.ui.Button, interaction: discord.Interaction):
                await channel.send(embed=embed)
                


        # Create a message with the action row
        message  = await interaction.response.send_message(embed=embed, ephemeral=True, view=MyView())
    except Exception as e:
        # If an error occurs, the code inside this block will run
        # We'll use 'except Exception' to catch any type of exception

        # Get the traceback as a string
        traceback_str = traceback.format_exc()

        # Create the error message you want to send to Discord
        error_message = f"An error occurred:\n```\n{traceback_str}\n```"

        # Send the error message to Discord using a POST request
        requests.post(DISCORD_WEBHOOK_URL, json={"content": error_message})`
turbid condor
#

!code

unkempt canyonBOT
#
Formatting code on discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

buoyant quail
#

Run code

import discord
print(discord.__version__)
print(dir(discord.Embed))

and show the output

slate swan
smoky patrol
slate swan
cinder horizon
#

wt i wanna do is get my bot to leave evry server its in but for the one wer im running da command........

@bot.command(pass_context=True)
async def die(ctx):
    for guild in bot.guilds:
        if guild.id == 964147453160984638:
            pass
        else:
            await guild.leave()
            print(f"Left {guild.name}")

but neither do i get a response nor an error........wer am i wrong?

buoyant quail
#

pass_context brainmon

smoky patrol
# slate swan did you run the code above?

2.4.0a
['bool', 'class', 'delattr', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'init_subclass', 'le', 'len', 'lt', 'module', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'slots', 'str', 'subclasshook', '_author', '_colour', '_fields', '_footer', '_image', '_provider', '_thumbnail', '_timestamp', '_video', 'add_field', 'author', 'clear_fields', 'color', 'colour', 'copy', 'description', 'fields', 'footer', 'from_dict', 'image', 'image_urlset_thumbnail', 'insert_field_at', 'provider', 'remove_author', 'remove_field', 'remove_footer', 'set_author', 'set_field_at', 'set_footer', 'set_image', 'thumbnail', 'timestamp', 'title', 'to_dict', 'type', 'url', 'video']

cinder horizon
slate swan
#

it doesnt exist any more

buoyant quail
smoky patrol
#

huh

cinder horizon
buoyant quail
smoky patrol
#

wdym

buoyant quail
smoky patrol
#

i copyed from output

slate swan
buoyant quail
#

interesting

slate swan
unkempt canyonBOT
smoky patrol
buoyant quail
#

2.4.0a??

slate swan
#

2.4.0

smoky patrol
#

im from the future

slate swan
#

could be dev version

cinder horizon
#

.... :c so much to change eh....

buoyant quail
#

Try downgrade to the latest stable version

cinder horizon
#

last i used was 1.7.3 :))

buoyant quail
#

pip install discord.py==2.3.1

smoky patrol
#

pip : Die Benennung "pip" wurde nicht als Name eines Cmdlet, einer Funktion, einer Skriptdatei oder eines ausfรผhrbaren Programms erkannt. รœberprรผfen Sie die Schreibweise des Namens, oder ob der Pfad korrekt ist (sofern enthalten), und
wiederholen Sie den Vorgang.
In Zeile:1 Zeichen:1

  • pip install discord.py==2.3.1
  •   + CategoryInfo          : ObjectNotFound: (pip:String) [], CommandNotFoundException
      + FullyQualifiedErrorId : CommandNotFoundException
slow fog
#

same*

smoky patrol
#

wtf is going on with my vsc

buoyant quail
slow fog
#

and i still use it till this day for personal use

smoky patrol
#

with pip

buoyant quail
#

try python -m pip install discord.py==2.3.1

smoky patrol
#

python : Die Benennung "python" wurde nicht als Name eines Cmdlet, einer Funktion, einer Skriptdatei oder eines ausfรผhrbaren Programms erkannt. รœberprรผfen Sie die Schreibweise des Namens, oder ob der Pfad korrekt ist (sofern
enthalten), und wiederholen Sie den Vorgang.
In Zeile:1 Zeichen:1

  • python -m pip
  •   + CategoryInfo          : ObjectNotFound: (python:String) [], CommandNotFoundException
      + FullyQualifiedErrorId : CommandNotFoundException
smoky patrol
# slate swan `python3` then

python3 : Die Benennung "python3" wurde nicht als Name eines Cmdlet, einer Funktion, einer Skriptdatei oder eines ausfรผhrbaren Programms erkannt. รœberprรผfen Sie die Schreibweise des Namens, oder ob der Pfad korrekt ist (sofern
enthalten), und wiederholen Sie den Vorgang.
In Zeile:1 Zeichen:1

  • python3 -m pip install discord.py==2.3.1
  •   + CategoryInfo          : ObjectNotFound: (python3:String) [], CommandNotFoundException
      + FullyQualifiedErrorId : CommandNotFoundException
buoyant quail
#

py -m pip is the last hope

slate swan
#

dev version:

smoky patrol
buoyant quail
buoyant quail
#

with py -m pip

slate swan
# buoyant quail check out embed
['__bool__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__len__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '_author', '_colour', '_fields', '_footer', '_image', '_provider', '_thumbnail', '_timestamp', '_video', 'add_field', 'author', 'clear_fields', 'color', 'colour', 'copy', 'description', 'fields', 'footer', 'from_dict', 'image', 'insert_field_at', 'provider', 'remove_author', 'remove_field', 'remove_footer', 'set_author', 'set_field_at', 'set_footer', 'set_image', 'set_thumbnail', 'thumbnail', 'timestamp', 'title', 'to_dict', 'type', 'url', 'video']
``` nope its normal
smoky patrol
#

i think i overwrote it somehow

buoyant quail
#

You easily can

#

If you will get in there for some reason

cinder horizon
cinder horizon
buoyant quail
#

Do you have message content intent enabled?
In the bot and on the website

slate swan
cinder horizon
#

hv enabled n don hv on message event

naive briar
#

!d discord.Intents.message_content

unkempt canyonBOT
#

Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:

โ€ข The message was sent by the client

โ€ข The message was sent in direct messages

โ€ข The message mentions the client

This applies to the following events...

naive briar
#

Have you enabled it in the code?

buoyant quail
cinder horizon
slate fiber
#

Can someone tell me how to get the voice channel name the bot is connected to from within an app command? (Using discord.py)

slate swan
unkempt canyonBOT
buoyant quail
#

!d discord.Guild.voice_client

unkempt canyonBOT
#

property voice_client```
Returns the [`VoiceProtocol`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceProtocol "discord.VoiceProtocol") associated with this guild, if any.
buoyant quail
slate fiber
slate fiber
# unkempt canyon

And this just returns <member 'name' of 'VocalGuildChannel' objects>

slate swan
#

you are supposed to call this on VoiceChannel instance

#

not VoiceChannel class

buoyant quail
#

Which has name

slate fiber
slate swan
#

i do

slate fiber
#

Aight lemme try it again

slate swan
buoyant quail
#

!d discord.VoiceClient.channel

unkempt canyonBOT
slate fiber
# unkempt canyon

This works if I have the return variable from VoiceChannel.connect()

buoyant quail
#

This returns the same value that you get from connect

slate fiber
#

Alright lemme try again again

#

'property' object has no attribute 'channel'

#

Am I being that stupid

buoyant quail
#

you need not the guild class, but it's instance

slate fiber
#

Got it

#

Finally

#

Thanks a lot

#

The fact that my editor still doesn't show it as an attribute of voice_client didn't help

buoyant quail
#

Maybe because it's optional

#

So your editor can't be sure that it's a VoiceClient

slate fiber
#

Maybe. And it's still complaining that name doesn't exist on type 'Connectable'

buoyant quail
#

?

slate fiber
#

The linter is still showing an error even though it works

buoyant quail
#

Maybe there is something dynamic generated

slate fiber
#

Probably, though it should have accounted for all possible defined attributes

#

Anyways, it works

stark gull
#

I am a beginner in programming. Currently I want to create a bot and have to download discord.py but I can't download . can anyone show me.
sorry to bother

thin raft
#

tf is your pfp

stark gull
stark gull
thin raft
turbid condor
stark gull
turbid condor
#

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

turbid condor
outer flint
#

when I send this message

message = f"\`\`\`html \n{monument} \n---------\n "
await inter.send(f"{message}\`\`\`")

it doesn't display the code block as html but instead writes it directly thonkhmm

any idea why?

i thought the problem was ```ansi, so I switched to ```html thonkhmm

buoyant quail
#

Why did you escape the ` symbols if you want a codeblock?

#

```html

```

#
-----
outer flint
#

I escape for the purpose of printing it here kek

buoyant quail
#

So it's normal there?

outer flint
#

this is how it looks

buoyant quail
#

It doesn't color it or it doesn't display it as codeblock?

#

(language shouldn't have the space between it and new line)

#

but it still should show it as codeblock, but without color

hasty pike
#

Can i get entry.user.roles in on_audit_log_entry_create(entry) ??

buoyant quail
#

If it is a member object

#

!d discord.AuditLogEntry.user

unkempt canyonBOT
hasty pike
#

Idk about that

#

So i can right

buoyant quail
#

You need to check it in the code. It can be both

hasty pike
#

How can i check?

buoyant quail
#

!d isinstance

unkempt canyonBOT
#

isinstance(object, classinfo)```
Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") exception is raised. [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") may not be raised for an invalid type if an earlier check succeeds.

Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union).
hasty pike
#

isinstance(entry.user, discord.Member)

buoyant quail
hasty pike
buoyant quail
#

Leaved from the server

hasty pike
#

I just want to remove roles so i can let it be without checking

buoyant quail
#

You would get an attribute error if it is a user

hasty pike
#

๐Ÿ’€๐Ÿ‘

#

I'll check

hasty pike
#

@buoyant quail

buoyant quail
#

Missing Permission means you don't have permissions to do that, nothing special
Unknown role is some magic idk how did you got it
Ratelimit is because you send too much requests

remove_roles takes any count of roles and makes one request
but you are making a request for each role

slate swan
#

meaning you can jus pass user.roles

hasty pike
#

So missing permission no chance

buoyant quail
#

Check out what role it is

slate swan
#

if the role is above in hierarchy it is possible

hasty pike
hasty pike
slate swan
slate swan
hasty pike
#

Wait

#

So i should change entry.user.roles to user.roles

slate swan
#

no

buoyant quail
slate swan
#

i just didnt type entry.

hasty pike
slate swan
#

and what is it

hasty pike
#

@buoyant quail unknown role is for @everyone role

hasty pike
slate swan
#

if you dont want it you just do .roles[1:]

hasty pike
#

Shoya is bot's integration role

#

So skip

#

Rest 2 are normal roles and below bot

slate swan
#

so it obviously cannot remove role for itself

slate swan
hasty pike
#

I get it now

#

@slate swan how about trying member.edit(roles=None) unclelaugh unclelaugh

buoyant quail
#

I'd guess roles=[]

slate swan
#

!d discord.Member.edit

unkempt canyonBOT
#

await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timed_out_until=..., bypass_verification=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the memberโ€™s data.

Depending on the parameter passed, this requires different permissions listed below...
slate swan
#

yep i belive empty list could work

buoyant quail
#

Removing everyone hmm :p

#

But i guess discord will just add it

#

It's not even an actual role

#

bruh

slate swan
#

dam

buoyant quail
#

@ะตvะตryonะต

unkempt canyonBOT
#

discord/member.py lines 894 to 895

if roles is not MISSING:
    payload['roles'] = tuple(r.id for r in roles)```
slate swan
#

None wont work but empty list should

buoyant quail
#

roles=discord.utils.MISSING

slate swan
#

if it will be MISSING then this if wont happen

hasty pike
#

Thanks

#

@slate swan

buoyant quail
#

The same reason here as in the removing

#

By doing it you are trying to remove the role you can't remove

hasty pike
#

I should make 2 isinstance

#

One for everyone and another for integration roles

buoyant quail
#

fyi roles have a method fot it

hasty pike
#

๐Ÿ˜‚

#

Easy now

slate swan
#

!d discord.Role.is_integration

unkempt canyonBOT
#

is_integration()```
[`bool`](https://docs.python.org/3/library/functions.html#bool "(in Python v3.11)"): Whether the role is managed by an integration.

New in version 1.6.
hasty pike
#

if role.is_assignable():
user.remove_roles(role)

#

Inside for loop

slate swan
#

what an integration is ๐Ÿ˜ตโ€๐Ÿ’ซ

buoyant quail
hasty pike
buoyant quail
#

then for what is_premium_subscriber() is?

slate swan
#

so integration is most likely a bots role

hasty pike
#

Discord recently introduced this

buoyant quail
#

linked role?

slate swan
#

yeah was thinking if its about this new feature or what the integration is

hasty pike
slate swan
buoyant quail
#

profile integrations exist

#

connections*

hasty pike
slate swan
#

easiest example i can come up with:
you have some levels in game and want users to have desired role for each level range like 0-9 role1, 9-19 role2, ... you can do it easily with linked roles if the game has an api

#

i prolly cant post a docs for this feature for hypixel server

#

https://docs.polsu.xyz/polsu/linked-roles

#

i can

buoyant quail
#

interesting

hasty pike
#

Very interesting

buoyant quail
#

and you can create any by yourself?

#

or only some popular apps

hasty pike
hasty pike
#

Basically partnered

buoyant quail
#

There is hypixel in profile?

#

nope

slate swan
buoyant quail
#

cool

hasty pike
slate swan
#

it will just assign roles based on requirements

hasty pike
#

Interesting concept

slate swan
#

i was in hypixel community for a long time and such bots that handle the hypixel roles for range of some levels in some gamemode were popular

#

now its built in to discord and easy to use

hasty pike
#

I see

slate swan
#
import discord
from discord.ext import commands

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

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

@bot.event
async def on_ready():
    print(f"Logged in {bot.user.name} ({bot.user.id})")
    print("Ready")

@bot.event
async def on_message(message):
    print(message.content)

bot.run(token)
#

why message.content is empty?

unkempt canyonBOT
#
Discord Message Content Intent

The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."

The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.

Privileged intents, such as message content, have to be explicitly enabled from the Discord Developer Portal in addition to being enabled in the code:

intents = discord.Intents.default() # create a default Intents instance
intents.message_content = True # enable message content intents

bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor

For more information on intents, see /tag intents. If prefix commands are still not working, see /tag on-message-event.

buoyant quail
#

@slate swan ^

main holly
#

i need help making my discord bot

#

like my commands will not show up

slate swan
#

Post your code and any errors you get then

main holly
#

i dont have any errors

#

they jus dont show up

#

and hold on im doin sometthing rn ill be back at my pc in a sec

main holly
slate swan
#

What

main holly
#

bruh

slate swan
#

did you enable this?

main holly
#

yep

slate swan
#

i have same problem

buoyant quail
#

And bezzer is talking about slash command as i understood

buoyant quail
#

message content

main holly
#

import discord
from discord.ext import commands

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

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

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

@bot.command()
async def kick(ctx, member: discord.Member, reason=None):
if ctx.author.guild_permissions.kick_members:
await member.kick(reason=reason)
await ctx.send(f'{member.mention} has been kicked.')
else:
await ctx.send('You do not have permission to kick members.')

@bot.command()
async def ban(ctx, member: discord.Member, reason=None):
if ctx.author.guild_permissions.ban_members:
await member.ban(reason=reason)
await ctx.send(f'{member.mention} has been banned.')
else:
await ctx.send('You do not have permission to ban members.')

@bot.command()
async def mute(ctx, member: discord.Member):
role = discord.utils.get(ctx.guild.roles, name='Muted')
if not role:
role = await ctx.guild.create_role(name='Muted')

await member.add_roles(role)
await ctx.send(f'{member.mention} has been muted.')

bot.run('') <-- my token is here but i didnt wanna put it here

buoyant quail
#

it's not it

buoyant quail
slate swan
#

YES I HAVE

unkempt canyonBOT
#
Discord Message Content Intent

The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."

The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.

Privileged intents, such as message content, have to be explicitly enabled from the Discord Developer Portal in addition to being enabled in the code:

intents = discord.Intents.default() # create a default Intents instance
intents.message_content = True # enable message content intents

bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor

For more information on intents, see /tag intents. If prefix commands are still not working, see /tag on-message-event.

slate swan
#

thank you

main holly
#

ohh

#

wait

#

i forgot its a prefix

#

anddd it doesnt work still

buoyant quail
#

Show what you changed.

main holly
#

i didnt know what to change

#

i had it like that already

#

how do i enable message intent

slate swan
#

Look at the tag above

#

And don't get messages confused with message_content

main holly
#

wdym

slate swan
main holly
#

this is starting to piss me off

#

idk if i can do this

#

Privileged message content intent is missing, commands may not work as expected.

#

idk how to do this

slate swan
main holly
#

i think i fixed it

#

intents.message_content = True

#

i added this

#

it doesnt show the warning anymore

#

i think thats a score

main holly
main holly
#

with prefix?

buoyant quail
#

!d discord.Member

unkempt canyonBOT
#

class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").

This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").

x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.

x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.

hash(x) Returns the memberโ€™s hash.

str(x) Returns the memberโ€™s handle (e.g. `name` or `name#discriminator`).
buoyant quail
#

add_roles and remove_roles

main holly
#

or woman

main holly
buoyant quail
#

!d discord.ext.commands.Bot.change_presence

unkempt canyonBOT
#

await change_presence(*, activity=None, status=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Changes the clientโ€™s presence.

Example

```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
```   Changed in version 2.0: Removed the `afk` keyword-only parameter...
main holly
main holly
#

how do i put an "add to server" button on the bots thing

#

crap

buoyant quail
#

On the bot page

#

in discord developers site

main holly
#

wheres

#

where *

#

on dev portal?

buoyant quail
#

yes

main holly
#

yea i checked

#

there was no add to portal

#

OH wait

#

the public bot thing was checked

#

oh itโ€™s supposed to be checked

#

got it

#

thanks

true dawn
#

Is there a way to make a command making an embed require a list/dictionary or context in order to send out a working embed with the text in the embed itself?

main holly
#

bruh

true dawn
#

My python rusty

#

like 3 years rusty

#

I forgot

main holly
#

same

#

i forgot how to code in python

true dawn
#

if I see it, and replicated it, then tweak the code to how I need it, I'm fine. I just need to see how it works first.

main holly
#

how do i make a timeout command ๐Ÿ˜ญ

main holly
main holly
buoyant quail
#

Why can't you open the docs by yourself? pithink

#

!d discord.Member.timeout

unkempt canyonBOT
#

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

Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.11)").

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

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
true dawn
#

I have the doc page open, but I am so lost

main holly
main holly
#

bro

#

idk how to make it show the membercount

#

on its status

echo summit
#

yoo can anyone help me with my music bot

ornate sapphire
#

anyone know how ot make a discord bot tell you how many members are in your server?

true dawn
#

new idea. how do I make a command where you can ask a question, the person using the command inputs text, and it returns pings of members? (first code) ```
import discord
from discord.ext import commands

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

@bot.event
async def on_ready():
print("Ready to ping!")

@bot.command(aliases= ["a", "b", "c"])
async def ping(ctx, member:discord.Member = None):
if member == None:
member = ctx.author

pinged = get(ctx.guild.roles, name = "Ping")

embed = discord.Embed(title = "title here", description = "Let's Go!", colour = discord.Colour.random())

await ctx.send(embed=embed)
await ctx.send(f"{pinged.mention})

await ctx.message.delete()

I want to change this to make a command that instead of an embed, it sends out a question, and it receives a group of members, and reiterates/pings the members it received back in discord.
main holly
#

hey how do i put the amount of servers on my bots status

twilit grotto
main holly
#

idk how to make a timeout cmd

slate swan
unkempt canyonBOT
#

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

Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.11)").

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

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
main holly
slate swan
#

So what's the part you're struggling with

main holly
#

i suck at this

#

im tryna make a discord bot and idrk what to do

#

for timeout

#

i have ban, kick, and mute and they all work but timeout just sucks

slate swan
#

ducky_blurp That doesn't tell us what your issue actually is

slate swan
#

Anyone help regarding these when i scrap answer it overlaps some syntax

#

@slate swan

charred vector
#

anyone know how to set the bot up to send out going live notifications for twitch? ive tried a few different things and nothings working so far any help would be appreciated pika_heart_1 pika_heart_2

slate swan
unkempt canyonBOT
#

await change_presence(*, activity=None, status=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Changes the clientโ€™s presence.

Example

```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
```   Changed in version 2.0: Removed the `afk` keyword-only parameter...
slate swan
#

You'd use this and call the len() function on client.users, iirc.

slate swan
sharp whale
#

how do i have slash commands in cogs

#
class testCog(commands.GroupCog, group_name='testcog'):
    def __init__(self, bot):
        self.bot = bot
    
    @app_commands.command(name="ping", description="SHOWS THE PING")
    async def ping(self, interaction):
        latency = self.bot.latency
        await interaction.response.send_message(f"{latency*1000:.2f}ms")``` not working
buoyant quail
#

You are not loading the cog at all
or
You are not syncing the commands

sharp whale
sharp whale
#

and i synced too

buoyant quail
# sharp whale and i synced too
import discord
from discord.ext import commands

intents = discord.Intents.all()
bot = commands.Bot(".", intents=intents)


class testCog(commands.GroupCog, group_name='testcog'):
    def __init__(self, bot):
        self.bot = bot

    @app_commands.command(name="ping", description="SHOWS THE PING")
    async def ping(self, interaction):
        latency = self.bot.latency
        await interaction.response.send_message(f"{latency * 1000:.2f}ms")


@bot.event
async def setup_hook():
    await bot.add_cog(testCog(bot))
    guild = discord.Object(id=703325198086307860)
    bot.tree.copy_global_to(guild=guild)
    await bot.tree.sync(guild=guild)


bot.run(TOKEN)
#

everything is fine by me