#discord-bots
1 messages ยท Page 273 of 1
Discord.js = JavaScript?
And is it true that it does not require a database?@slate swan
what
- yes
- this question makes no sense
I mean, if you create an economy for yourself, you don't need to download a database, is it easier?
its the same hard as in python if you wish to not use database
If you want then use
Ye
No one is stopping you
databases are independent of the programming language
and you can use a file based one like sqlite
keep in mind that you wont get help about javascript in this discord server
I can create a datebase file
On python
sqlite database is a single file without anything
I believe mobiles can create and write into files
Datebase?
.
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 ')```
oh ok
Working with list โ
Working with it's representation and regex 

how would i get the embeds field value that a button is attached to when a button is clicked
u would have to edit the embed in the button callback
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
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
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?
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()```
It will not be able to receive the command in the first place
is that true for app commands?
Because I can call the command in a channel the bot can't see
You can disable the commands in that channel via settings
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:
did you save the file and re run the bot?
i mean it has a url on it but I couldn't really share it
If you save and re-run the bot and run the command again, the URL will go away
@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
I don't know if you can make colors on URL buttons
also quick question, does view.wait() make it wait until the button is clicked?
You can't do that with link buttons either
oh damn lmao
Link buttons are very restrictive in that they're just UI components, they just act as fancy hyperlinks
!d discord.ui.View.wait
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.
They don't have callbacks or events or colors or anything like that
i mean the link is a discord oauth link
its like for verifying people
and like i swear ive seen something
doesnt matter what link it is
Then you can detect it when they get redirected back to your webserver with the authorization code grant
you just cant have a callback on such button
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
but would the bot and the server not have to be running on the same file or pc even?
no why would it
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.
!intents
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.
You're probably missing message_content intent
๐ญ
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
You get the message content if A) it's in a DM and B) if the bot is pinged in the message
Do you have it enabled in the developer dashboard as well?
Yeah lol ... My bot is actually administrator privileges
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:)
what kind of bot - feel free to dm me
I want to create discord crypto wallet bot but idk which api I can use for crypto Transaction 
Can anyone help me to create that type of bot ?
discord crypto wallet bot
what?
Means we can send crypto using bot Command for example:
/send amount address note
That sounds very secure-
Do you have any idea which api I can use for it ?
Why would anyone use this?
Like why would people let you access their crypto wallets and money?
I dont think you've thought this through
Idk my one client want that type of bot, they give good amount for it
^
actually they have marketing server so that bot can help them to do fast and easy Transactions
@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'

Are you using discord_components??
yea but I decided to change to pycord
but I dont know if it will work with my slash commands
๐คก
Better read docs
Discord components no longer works
You need discord view
Against Tos

that's why it said improper token?
I was just trying to store msg in a txt file from an active server
Self boting is against discord TOS you shouldn't do that
ik that, just for learning purpose
cuz I can't make my bot get added in active server
I want to store 100k msg from a server in txt file
I read the docs, its better for me than watching yt xd...
alright ty
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
Lol 
Components no longer support you should use discord view
eh?
Learn all about implementing buttons in your Discord Bot using Pycord.

FINALLYYYY, someone sent me this more accurate link ๐ญ
You could have just used search in docs
THANK YOUU ๐ญ
@copper gulch https://youtu.be/kNUuYEWGOxA
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...
Please, check this above msgs,
For different methods and better understanding
nah its fine, Ill use the docs better
He has mentioned all possible methods in video
Ill just save it in my bookmark. thanks you so muchh btw
And it's same for discord.py and nextcord (fyi)
@hasty pike crypto and blockchain ke bare me kuch idea hai ?
Never tried idk about any crypto api
Okk np 
What do you mean it's same for discord.py
View class methods is same for all three libraries
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
It's just about arguments you could change that
You could not change what arguments it gives
At least not without modifying how the view dispatch the items
Well i never had any issue in migrating
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()

Why do you think it's full command 
It's only lines with issue
๐ค
Whatโs his problem?
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')
Ahh
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
Try moving you view out of the cog
ok ok
also naming the class same as the class you want to subclass from isnt a good idea
yea Im changing it. its confusing me aswell xd
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
If you sent the error it would be easier to answer..
https://github.com/Rapptz/discord.py/blob/master/examples/views/counter.py#L28
here is the problem - you swapped the arguments
examples/views/counter.py line 28
async def count(self, interaction: discord.Interaction, button: discord.ui.Button):```
wait lemme rerun
AttributeError: 'Button' object has no attribute 'response'
^
thats for the button label... but what about the message?
here is the problem - **you swapped the arguments **
oh right
Makes sense tho ๐
interaction: comamnds.Context :p
and got it, tis solved
its fine xd...
atleast it works xd
Exactly that's what i meant
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
!e
class A:
def a(self, *, b):
print(b)
A().a(0)
@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
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!")
What library are you using
how can you use 2 libraries at once?
Well, are you using a third-party library to make slash commands
My bad, didn't read the full message
!d discord.TextChannel.history
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...
If it was discord.py
its not discord.py though
what should i be using? been a long time since i coded a discord bot, and as of last time i just used discord_slash, but that seems to not work anymore.
Ik
discord.py and other forks already have their native app commands implementation
PascalCase ๐๐๐
and their docs are very hard to read comparing to dpy
or maybe .ChannelHistory.fetch()
i am not sure there
imma look into this. thanks
megik
'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.'))
!d discord.User
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`).
because it doesn't have it
!d discord.Member
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`).
Member has
User not
If they were the same on of them would be useless ยฏ_(ใ)_/ยฏ
Does max_concurrency decorator not work for app_commands?
How can I do
async def on_message(msg):
in cogs?
!d discord.ext.commands.Cog.listener
I tried this
@commands.Cog.listener()
async def on_message(self, msg):
but didn't worked
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").
what didnt work mean?
if cog is not loaded obviously commands and events inside are not too
its interactions.py
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
!paste
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.
possible since I made a channel where it uses openai so people can ask it stuff
idk actually
I have no idea how rate limits work
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
oh?
it scans every message on the server
to check for some words
and the chats are pretty active especially minecraft chat
your code desperately needs a code formatter run over it btw...
I really recommend installing black
and just formatting everything
you install it then you have black command
you run it and specify path to files and it formats them
and do you know what couldve requested so much stuff that I got ratelimited for 8 hours
no idea im not very into interactions.py
yes
does sparkedhost use shared ips? that might be the reason for getting rate limited
I got dedicated ip just for that case
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
My eyes
๐ฐ
Hi can anyone help me?
...
How to remove line Red?
!d str.join
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.
!e
x = ["a", "b", "c"]
print(" * ".join(x))
@buoyant quail :white_check_mark: Your 3.11 eval job has completed with return code 0.
a * b * c
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
Don't like this
Here
Rand is a list of strings
Use that method on it.
How?
||Begin from learning python and not from making bots||
{' '.join(rand)}
Man not this
Didn't work
Show how it didn't work.
I've done that before
Then do again.
I want nothing in it
You can put anything you want
Nothing will work too
!e
x = ["๐", "๐", "๐"]
print("".join(x))
@buoyant quail :white_check_mark: Your 3.11 eval job has completed with return code 0.
๐๐๐
The forbidden coding method ๐ฐ ||(aka WET)||
hi
please how can i customize my embed fields like that :
like if i want to let it be in the middle etc..
mh ?
!d discord.Embed.add_field
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.
inline value
yeah thanks
Is it possible to do reply on message.channel.send()
!d discord.TextChannel.send
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**.
check reference parameter @hasty pike
In short
I can't
I needed something like ctx.reply()
But didn't find anyway to do it
why?
I did some research but didn't seem to find a way to do it
You can
you just need to pass a message object to reference
You just pass reference kwarg
Can you show me example?
You need a message you want to reply to and pass it as reference
So msg = author.message
msg.reply()
I dont think author have .message attrubute
You are supposed to do channel.send(..., reference=msg)
How do i find message?
I'm inside on_message
Find what message
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.
Reference=message?
Try
Should
Worked 
๐
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`.
!d json.load
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.
it is refering to the config.json
it needs to be a str
With load, I believe it needs to be a file object with open()
nah i always use this syntax and it works ..
show full code
my bad ur right i just check my other script and it's not the same lmfaaooooo
fp stands for file path idk if you necessarily needs a stream
sorry ๐
Read the first paragraph describing the method
json.load = file object
json.loads = text
there is no method for just filename
because it's kinda useless /
yeah mb
Although now Iโm wondering why they chose fp as the parameter
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`.)
Has discord.py any function to catch webhooks messages, instead of on_raw_message?
you could just check if the message is a webhook by seeing if it has a webhook_id
Using on_raw_message you mean?
Welp, thanks ๐
Are you using discord.py? - If so, there isn't an on_raw_message
ye forgot lol
i was talking about on_message
Then yes, you could do what I suggested in on_message as a simple check
role.position exists?
!d discord.Role.position
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.
it appears as if so
'Role' has no attribute 'position'
data = ([role for role in ctx.guild.roles])
data = sorted(data, key=lambda role:role.postion, reverse=True)
- 'Role' has no attribute 'position'
+ 'Role' has no attribute 'postion'
guys how can i make slash command option like discord.Option(discord.Member) but for channels selecting like that (pycord)
I can't be sure about pycord but just typehint it i guess
switch to discord.py then we can help
https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_options.py#L38-L46
well. not typehint, but give it to the some option thing
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],```
yeah i just wanted to know what did i have to put thx
or just typehint will work
https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_basic.py#L37
examples/app_commands/slash_basic.py line 37
async def joined(ctx: discord.ApplicationContext, member: discord.Member = None):```
you can test it
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 :
!e
A = [1, 2, 3]
print(A.append(4))
@buoyant quail :white_check_mark: Your 3.11 eval job has completed with return code 0.
None
oh
okok
ohh my bad
i didn't have to assign it to a variable my bad
yeah that's it @buoyant quail thx
are you coding in notepad?
nah i just edit the json file with notepad
why don't you open it with your code editor?
i don't see a real utility to open with vsc
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)
Generally you will put the database behind the API and interact with the database through the API
so if I make a REST API, I'll build everything I need in here, then have the bot make the requests ?
Pretty much
From a certain point of view your bot is simply a "front end"
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
Sure, discord.py ships with aiohttp which you can use to make requests to your API
If you have an OpenAPI spec you can generate SDK-like consumers for your API
oh great, ty ๐
Can sombody please tell my why i keep getting indent errors whith this https://paste.pythondiscord.com/WSLA
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
Tbh idk how to code im using chatgpt and its not as easy as i hoped
My code is here https://paste.pythondiscord.com/WSLA
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
will that fix the indented block errors
!resources I would recommend going through a beginner guide as this will be covered there
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
discord.py is unfortunately not really meant for beginners
@app_commands.is_owner() is not a thing? Does the library have an alternative or do I need to define a check
What timestamp
Discord timestamp
!d discord.utils.format_dt you mean this?
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...
like <T:00000000> like this?
Then this is it
thanks
!d discord.Embed.set_thumbnail
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.
guys i dont understand how to learn discord.py coding language
learn it
i dont even have the option
just learn with bots lol
wdym
learning by doing
discord.py is not a language it's a python package
bro im a begginer u dont need to make fun of me
I don't see how that's making fun of anyone
You need to learn more python before touching discord.py then
i know python basics
learn python then lmao
print("Hello World")
What about oops?
do you know what a token is?
for sure
its very dangerous to reveal to someone
u dont know
i never worked with classes can you recommend it?
Ideally you should be familiar with OOP and know a bit about async/await before using discord.py
Welp if you don't know oops then you are going to have a hard time with discord.py
i dont understand oop too
i worked always without it and everything works fine
I never said it won't work i just said you will be having a hard time
How far have u gone into the dpy?
If you know what instances are, then you already have some knowledge about OOP
wdym by that?
Like what have u worked on so far using that?
im working atm on slash commands, json to embed converter
Welp what about views?
never heard of it tell me more
components in messages
like keywords?
no like buttons dropdowns etc
And in simpler terms the buttons, drop downs etc
Buttons, drop-downs, ...
so i need to learn oriented object programming to begin to learn discord bot language ?
there is no discord bot language?
It's recommended to, but not required
that?
You'd just have a hard time if you don't
thats a button
what is a discord bot language?
yeah worked with it
idk its name
and you did no use classes?
no
you name it python btw
i meant python
but the discord one yk
Tbh there is no discord bot language it's a python library that u use
ok ty
And there is not one but many that u can use
but do you know what it does ?
not really can you explain me some stuff about classes so i understand the usage, i got it from the discord.ui docs
For example: discord.py, py-cord, nextcord and disnake and there might be others
Don't have to use any library 
That works too if u can manage
requests 
urllib
C language
golang ๐
Folders
slash commands are very bad
What
I guess he means their realization in that library
write your own wrapper 
golang is future for the other stuff
https://discord.com/developers/docs/topics/community-resources#libraries-discord-libraries
thats the only one golang library
Giga chad
i wanna code bots
ok

๐คฆ youtube videos are outdated
I wonder how many of them will be using JSON
Create your own and then watch them 
check the docs and examples on github if you really wanna learn something
All
he doesnt even know what discord.py is so
so?
it is better
so we will say him good luck
to understand it
thanks guys for help
They can learn it ๐คท
How is that better?
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
Whatโs image_url?
Is the image being shown in set_image?
Yes
I printed
And used set_image and it works, it is nothing with the url
Very weird
Can you put a print statement in your if condition where you are setting the thumbnail
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
Welp in the above ss you sent, the set_thumbnail will only be set when it satisfies the condition you set
Can u show the error
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.
And can you show the full command code
Fr reading code in image sux
At least not a photo from phone :\
I sent errors with webhooks
`@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})`
!code
Run code
import discord
print(discord.__version__)
print(dir(discord.Embed))
and show the output
bros using discord.py from the 1990
Why
did you run the code above?
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?
did you write this?
pass_context 
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']
......yes(?)
cause the pass_context=True is like 2 years old
it doesnt exist any more
wtf 'image_urlset_thumbnail'
huh
pls do note i hvnt coded in 2 yrs.......
It's exactly like this by you? Or it's only here?
wdym
i copyed from output
is this discord.py?
interesting
!pip discord.py
2.4.0a??
2.4.0
im from the future
could be dev version
.... :c so much to change eh....
Try downgrade to the latest stable version
last i used was 1.7.3 :))
pip install discord.py==2.3.1
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
wtf is going on with my vsc
How did you install it before?
and i still use it till this day for personal use
with pip
try python -m pip install discord.py==2.3.1
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
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
py -m pip is the last hope
dev version:
worked
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
i think i overwrote it somehow
so do i...
took out pass context n still doesnt work.......wut do i do?
Do you have message content intent enabled?
In the bot and on the website
either you did not enable message_content or you have on_message event
hv enabled n don hv on message event
!d discord.Intents.message_content
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...
Have you enabled it in the code?
Show full code
my bad...............thot i had intents=discord.Intents.all()........twas set to intents = discord.Intents.default()
Can someone tell me how to get the voice channel name the bot is connected to from within an app command? (Using discord.py)
The channel name.
!d discord.Guild.voice_client
property voice_client```
Returns the [`VoiceProtocol`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceProtocol "discord.VoiceProtocol") associated with this guild, if any.
and ^
This doesn't have a name property
And this just returns <member 'name' of 'VocalGuildChannel' objects>
This does have a channel property
Which has name
I don't see a channel property
i do
Aight lemme try it again
!d discord.VoiceClient.channel
The voice channel connected to.
This works if I have the return variable from VoiceChannel.connect()
Alright lemme try again again
'property' object has no attribute 'channel'
Am I being that stupid
same as this
you need not the guild class, but it's instance
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
Maybe. And it's still complaining that name doesn't exist on type 'Connectable'
?
The linter is still showing an error even though it works
Maybe there is something dynamic generated
Probably, though it should have accounted for all possible defined attributes
Anyways, it works
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
Oh. So how can I make a discord bot
Just the peaches :))
you should first learn how to code in python
Do you have knowledge regarding oops?
Can you give me some advice
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

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 
any idea why?
i thought the problem was ```ansi, so I switched to ```html 
I escape for the purpose of printing it here 
So it's normal there?
this is how it looks
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
Can i get entry.user.roles in on_audit_log_entry_create(entry) ??
You need to check it in the code. It can be both
How can i check?
!d isinstance
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).
isinstance(entry.user, discord.Member)
And what does it mean unless it's gone?
Leaved from the server
I just want to remove roles so i can let it be without checking
You would get an attribute error if it is a user
@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
meaning you can jus pass user.roles
Bot has administration in testing server
So missing permission no chance
Check out what role it is
if the role is above in hierarchy it is possible
I'm inside on_audit_log_entry_create
Bot has topest possible role I'm testing in proper environment
i dont see how does it restricts that
print out what role is causing it and debug it a bit
no

i just didnt type entry.
and what is it
it always is
I'll skip that
if you dont want it you just do .roles[1:]
so it obviously cannot remove role for itself
but the rest one has been already rate limited

I get it now
@slate swan how about trying member.edit(roles=None)

I'd guess roles=[]
!d discord.Member.edit
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...
yep i belive empty list could work
Removing everyone hmm :p
But i guess discord will just add it
It's not even an actual role
bruh
dam
@ะตvะตryonะต
discord/member.py lines 894 to 895
if roles is not MISSING:
payload['roles'] = tuple(r.id for r in roles)```
None wont work but empty list should
roles=discord.utils.MISSING
if it will be MISSING then this if wont happen
The same reason here as in the removing
By doing it you are trying to remove the role you can't remove
!d discord.Role.is_integration
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.
what an integration is ๐ตโ๐ซ
Server booster is integration role ๐คง
then for what is_premium_subscriber() is?
Or a linked role
Discord recently introduced this
linked role?
yeah was thinking if its about this new feature or what the integration is
role Linked to Spotify or other platforms?
yeah you can create roles based on some requirements
You can claim linked roles based on your connections
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
interesting
Very interesting
Ig you can
Not popular but for those you have in profile connections
Basically partnered
you can create your own and people can use it if you let them
cool
Nope ig
no it wont show that in profile
it will just assign roles based on requirements
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
I see
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?
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 ^
Post your code and any errors you get then
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
do i need a separate thing of code to register them?
What
bruh
did you enable this?
yep
i have same problem
You don't have message content enabled inside the bot.
And bezzer is talking about slash command as i understood
message content
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
it's not it
well, then the same issue
YES I HAVE
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.
Show what you changed.
i didnt know what to change
i had it like that already
how do i enable message intent
wdym
this
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

i think i fixed it
intents.message_content = True
i added this
it doesnt show the warning anymore
i think thats a score
i did it man thanks so much
how can i make an add role and remove role
with prefix?
!d discord.Member
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`).
add_roles and remove_roles
what abt custom status
!d discord.ext.commands.Bot.change_presence
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...
sorry i figured it out
but the real question is
how do i put an "add to server" button on the bots thing
crap
yes
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
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?
bruh
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.
how do i make a timeout command ๐ญ
??
^^
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").
I have the doc page open, but I am so lost
same ๐ญ
yoo can anyone help me with my music bot
anyone know how ot make a discord bot tell you how many members are in your server?
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.
hey how do i put the amount of servers on my bots status
create a task, which will update every x minutes or seconds, and set the status to something you want and just add len(client.guilds) i believe it is, dont quote me, i didnt look, but as far as i remember thats it
ok i did it and it works
idk how to make a timeout cmd
!d discord.Member.timeout
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").
i know
So what's the part you're struggling with
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
That doesn't tell us what your issue actually is
Anyone help regarding these when i scrap answer it overlaps some syntax
@slate swan
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

!d discord.Client.change_presence
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...
You'd use this and call the len() function on client.users, iirc.
You'd probably need to look at the Twitch API for that https://dev.twitch.tv/docs/api/
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
@slate swan halp pls
You are not loading the cog at all
or
You are not syncing the commands
the prefixed command works but slash command not working
i have a command which syncs the slash commands in main.py
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



