#discord-bots
1 messages · Page 1008 of 1
is that correct?
@commands.has_permissions(administrator=True)
this
You guys mean has_guild_permissions
!d discord.ext.commands.has_permissions
@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of
the permissions necessary.
Note that this check operates on the current channel permissions, not the
guild wide permissions.
The permissions passed in must be exactly like the properties shown under
[`discord.Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions")...
how can i send a message?
lets say i have a command called !announce, and i want it to send a message in #announcements, how could i make it send a message in #announcements and not respond in the same channel i gave the command?
the only way i know to send messages is
await message.channel.send("announcement!")
i assume the channel id is the name of the channel?
You see, message.channel is a discord.TextChannel object, that's why you can use send() on it.
Another way to get a discord.TextChannel like message.channel is to use bot.get_channel(id) or client.get_channel(id), like this:
channel = bot.get_channel(343944376055103488) #343944376055103488 is the id of the discord-bots channel we're in
After you have this channel variable which stores a discord.TextChannel object, you can use send() on this too.
channel = bot.get_channel(343944376055103488)
await channel.send("Hello!")
Traceback (most recent call last):
File "c:\Users\bopae\Downloads\Self made\Random\s4u bot\crypto.py", line 42, in <module>
client = commands.Bot(command_prefix="-")
TypeError: __init__() missing 1 required keyword-only argument: 'intents'```
pls help
You need to pass intents aswell
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
How to enable all intents again?
discord.Intents.all()
thx a lot
pinable?
thanks
and thanks to Hau
Man I just spent a good 10 minutes trying to tell this dude that he has to define a function to call it and that calling a random ass function won’t magically work
!e
print("Hello!")
@heady sluice :white_check_mark: Your eval job has completed with return code 0.
Hello!
Hi
called a random ass function
He’s wondering why “do_my_bullshit()” doesn’t do what he wants it to do magically
you didn't put anything in open_account
Your code 💀
put there what you want it to do
This is the dude, I’ve explained to him that it won’t magically work
I usually just put pass if I don't know yet
That’s what I told him 💀
Sigma grindset
def open_account():
pass
you can edit it later
or use ellipsis 😳
Oh no
It’s not gonna magically work since you defined the function
why make a function you arent gonna use
You need to program what you want it to do
how can i make my bot give users roles?
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to
use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list
of roles than the highest role of the member.
thanks
help
im using reddit's api to send posts from r/tifu
sometimes the posts exceed the 4018 character limit
im trying to split the paragraph in half and send it in 2 embeds if it does
!e ```py
text = "That is quite unfortunate."
print(text[:10])
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
That is qu
!e
print(len("Hello World!") > 2018)
@heady sluice :white_check_mark: Your eval job has completed with return code 0.
False
!e ```py
text = "That is quite unfortunate."
print(text[:7] + "...")
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
That is...
Slices
i see
IT'S ENOUGH SLICES
Give up on English too ig
Seems a bit hard for you too
Hm that was mean
Don’t give up on your code
Learn
bruh
Bruh 💀

command example ?
What is your problem
You don’t know how to code?
We’ll go and fix that yourself
Eh sorry I’ve had a lot of bullshit today
hmm one more question
Ask away
i need to .split the paragraph while keeping the word
Round it ig
you don't split it
for example:
selftext = """
sit amet nisl suscipit adipiscing bibendum est ultricies integer quis auctor elit sed vulputate mi sit amet mauris commodo quis imperdiet massa tincidunt nunc pulvinar sapien et ligula
"""
selftext_list = selftext.split(" ")
num = len(selftext_list) // 2
txt = selftext_list[:num][-1]
txt1 = selftext.split(txt)
desc1, desc2 = txt1[0], txt1[1]
this is what i have rn
Raise the error
then what
text[:10]
hi
Yo
hi mina
!e
selftext = """
sit amet nisl suscipit adipiscing bibendum est ultricies integer quis auctor elit sed vulputate mi sit amet mauris commodo quis imperdiet massa tincidunt nunc pulvinar sapien et ligula
"""
print(selftext[:40])
print(selftext[41:])
hey
god I messed up
hi mina, hi brad
hihi
selftext wont be the same each time
@heady sluice :white_check_mark: Your eval job has completed with return code 0.
001 |
002 | sit amet nisl suscipit adipiscing biben
003 | um est ultricies integer quis auctor elit sed vulputate mi sit amet mauris commodo quis imperdiet massa tincidunt nunc pulvinar sapien et ligula
guys
im getting posts from reddit
so some will be longer than others
It’s fine in the context
It would redirect you to bot commands if you couldn’t use it here
yeah it's not great, you have to split the text between two words
its not.
it is
you guys are just showing index slices
it's literally showing the other how stuff works
when its really not that hard?
And?
bro
its literally just indexing
and?
its not related to the topic of this channel.
sure
the lorem ipsum stuff was just a sample text
He was asking in context of his discord bot
bro
its index slicing
it's not like there are other stuff going on in the channel we could talk about
.topic
**Do you think there's a way in which Discord could handle bots better?**
Suggest more topics here!
!e ```py
def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):
yield lst[i:i + n]
selftext = """
sit amet nisl suscipit adipiscing bibendum est ultricies integer quis auctor elit sed vulputate mi sit amet mauris commodo quis imperdiet massa tincidunt nunc pulvinar sapien et ligula
"""
print(list(chunks(selftext, 10)))
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
['\nsit amet ', 'nisl susci', 'pit adipis', 'cing biben', 'dum est ul', 'tricies in', 'teger quis', ' auctor el', 'it sed vul', 'putate mi ', 'sit amet m', 'auris comm', 'odo quis i', 'mperdiet m', 'assa tinci', 'dunt nunc ', 'pulvinar s', 'apien et l', 'igula\n']
except Nakime's syntax errors
@commands.command()
async def tifu(self, ctx: commands.Context):
tifu = random.choice(tifu_list)
try:
embed = disnake.Embed(title=f"__{tifu.title}__", url=tifu.url, description=tifu.selftext, color=0x00FF00)
embed.set_author(name=ctx.author, icon_url=ctx.author.avatar)
embed.set_image(url=tifu.url)
await ctx.channel.send(embed=embed)
except:
selftext = str(tifu.selftext)
selftext_list = selftext.split(" ")
num = len(selftext_list) // 2
txt = selftext_list[:num][-1]
txt1 = selftext.split(txt)
desc1, desc2 = txt1[0], txt1[1]
embed = disnake.Embed(title=f"__{tifu.title}__", url=tifu.url, description=desc1, color=0x00FF00)
embed.set_author(name=ctx.author, icon_url=ctx.author.avatar)
embed.set_image(url=tifu.url)
await ctx.channel.send(embed=embed)
embed = disnake.Embed(description=desc2)
await ctx.channel.send(embed=embed)
💀
what
its a http error code bro
and realised it has to be at the start cuz the whole code is surrounded by error-eating try excepts
how to make it send User not muted when the user is not muted
nah
if not mutedRole in member.roles:
#do your thing
value = '{}'.format(member.mention) 
thx=)
no f strings and useless string convertion
i was referring to this ^^
cool
im not sure if you should talk about your infractions here as it probably should stay confidential and its not on topic.
You can talk about your warns
Not in the rules
doesnt mean its allowed
Let's just use common sense here and not talk about it...
i agree
It's not in the rules
Therefore nothing is stopping us from talking about it
Nobody gains anything from it, nobody loses anything if it is not spoken about. With the benefit of the doubt given, it's equably good (arguably better) to not talk about it.
Plus, not really related to discord bots...
background = Image.open("background.jpg")
asset = user.avatar_url_as(size = 128)
data = BytesIO(await asset.read())
pfp = Image.open(data)
pfp = mask_circle_transparent(pfp, 4)
pfp = pfp.resize((209, 209))
background.paste(pfp, (385, 160), pfp)
background.save("welcome.png")
await ctx.send(file=discord.File("welcome.png"))
Hi ! How can I send background without saving it as welcome.png ?
I do have a short question. I use buttons & dropdowns. But after several seconds, the button or dropdown menu wont respond anymore. I found this https://github.com/Rapptz/discord.py/blob/master/examples/views/persistent.py on the internet, but dont know what to do with it
seems like the line of code keeping it persistent is
super().__init__(timeout=None)
no
its making the view not timeout
the view class has it already as well lol
it makes it persistent because of the button custom ids
!d discord.ui.Button.custom_id
property custom_id```
The ID of the button that gets received during an interaction.
If this button is for a URL, it does not have a custom ID.
How to make the bot become a speaker when entering the stage channel?
@commands.command()
async def whitelisted(self, ctx):
if ctx.author is not ctx.guild.owner:
return await ctx.reply("You must be the guild owner to use this command")
else:
whitelisted = db.find_one({"_id": ctx.guild.id})["whitelisted"]
embed = discord.Embed(title="Whitelisted", description="",color=0x2f3136)
for i in whitelisted:
member = self.bot.get_user(i)
if member.id == 933235685001924618 or 957064940974407700:
embed.description + f":Badge_Developer: - {member.mention}\n"
else:
embed.description + f":Discord_Members: - {member.mention}\n"
embed.set_footer(text="Guild Owners are automatically whitelisted.")
await ctx.reply(embed=embed)
``` theres poeple in the whitelisted but its not bringing anything up
That or check in there a mild mistake btw.
!or-gotcha
When checking if something is equal to one thing or another, you might think that this is possible:
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
Yo can someone pls explain whats goin wrong 😅
Yo huh
Basically I used slash command and it gave me old code results
Like I've updated it 15 minutes ago, but it still gave me the old version
It doesn't even exist
still didnt help me w what im tryna do
TypeError: 'in <string>' requires string as left operand, not list
Code and full traceback
Traceback (most recent call last): File "C:\Users\ydzja\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 343, in _run_event await coro(*args, **kwargs) File "C:\Users\ydzja\Desktop\Dox Defender Developpement\main.py", line 200, in on_message if [str(ctx.guild.id)] not in ("antigrabify.json"): TypeError: 'in <string>' requires string as left operand, not list
Code
`@bot.listen()
@commands.has_permissions(administrator=False)
async def on_message(ctx):
Linkembed = discord.Embed(description="blabla.", title="this is an alert")
Linkembed.set_footer(text=f"yes | from {ctx.author}")
with open("antilinks.json", "r") as f:
setAntiLinks = json.load(f)
if [str(ctx.guild.id)] not in ("antilinks.json"):
setAntiLinks[str(ctx.guild.id)] = "off"
with open("antilinks.json", "w") as f:
json.dump(setAntiLinks, f, indent=4)
if "https://" in ctx.content.lower():
if setAntiLinks[str(ctx.guild.id)] == "on":
await ctx.delete()
await ctx.channel.send(embed=Linkembed)
await bot.process_commands(ctx)`
in antilinks.json :
@slate swan
I see the problem
First of all
Your doing “[string]”
Wait I’m confusing myself
I know what you have done wrong
Basically your saying if a list is in a string
Which is a no go
And you can’t open a file using (“file name”)
@tasks.loop(seconds = 5) # repeat after every 10 seconds
async def myLoop():
with open("count.stonks","r") as f:
count = int(f.read())
f.close()
channel = client.get_channel(903918973408665620)
channel.send("{count}")
myLoop.start()
gives error
Traceback (most recent call last):
File "C:\Users\allan\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\tasks\__init__.py", line 101, in _loop
await self.coro(*args, **kwargs)
File "C:\Users\allan\OneDrive\Documents\mootbot\cogs\Commands.py", line 753, in myLoop
channel.send("{count}")
AttributeError: 'NoneType' object has no attribute 'send'```
It hasn’t retrieved the channel object
how do i fix that
clients can't find channels iirc, is it a bot?
Ffs
?d commands.Bot.get_channel
how I should do this
bruh
why does it give me error but still work 
file path
!d discord.ext.commands.Bot.get_channel
No
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
oh..
oh haha
anybody know this? 🤔
Normally it would send a response message but you have sent a message to the channel
It expects a reply
srry wdym? 😅 so it needs to be a reply and not a new message?
If you don’t want the error send a blank response
I don’t mess with slash commands but it seems the be the same principle of interactions
This message is a reply, it expects you to send a reply instead of sending a message to the channel
hmm is reply
await ctx.reply(embed=embed)
``` instad of
``` await ctx.send(embed=embed)```?
aaah i see
Maybe
Yep
Ffs
still seems to b buggin 😅 i am gettin a ton of error messages, can i send a scrn shot?
Sure
Might be a bug with the slash command library your using
@tasks.loop(seconds = 5) # repeat after every 10 seconds
async def myLoop():
with open("count.stonks","r") as f:
count = int(f.read())
f.close()
channel = self.bot.get_channel(903918973408665620)
channel.send("{count}")
myLoop.start()
Unhandled exception in internal background task 'myLoop'.
Traceback (most recent call last):
File "C:\Users\allan\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\tasks\__init__.py", line 101, in _loop
await self.coro(*args, **kwargs)
File "C:\Users\allan\OneDrive\Documents\mootbot\cogs\Commands.py", line 752, in myLoop
channel = self.bot.get_channel(903918973408665620)
NameError: name 'self' is not defined
how tf
hmm i litrually only imported discord
weird.. aight i'mma have to check it up, ty! 😉
That has slash commands now?
Self is not defined!
seems so 😅
yea i know
'ApplicationContext' object has no attribute 'reply' 
but idk how to implement it
@tasks.loop(seconds = 5) # repeat after every 10 seconds
async def myLoop(self):
with open("count.stonks","r") as f:
count = int(f.read())
f.close()
channel = self.bot.get_channel(903918973408665620)
channel.send("{count}")
myLoop.start()
just gives
File "C:\Users\allan\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\tasks\__init__.py", line 101, in _loop
await self.coro(*args, **kwargs)
TypeError: myLoop() missing 1 required positional argument: 'self'```
You don’t need self
bot.get_channel works fine
Or you can use bot.fetch_channel
File "C:\Users\allan\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\tasks\__init__.py", line 101, in _loop
await self.coro(*args, **kwargs)
File "C:\Users\allan\OneDrive\Documents\mootbot\cogs\Commands.py", line 752, in myLoop
channel = bot.get_channel(903918973408665620)
NameError: name 'bot' is not defined
define it
client in your case
It’s your commands.Bot() variable
AttributeError: 'ApplicationContext' object has no attribute 'reply' ofc it does..? 😅
What library?
import discord
from discord.ext import commands
import asyncio
import logging
import datetime
import os
import re
import random
import json
import requests
from random import choice
import time
from discord.ext import tasks
client = discord.Client()
class Commands(commands.Cog):
def __init__(self, bot):
self.bot = bot
@tasks.loop(seconds = 5) # repeat after every 10 seconds
async def myLoop(self):
with open("count.stonks","r") as f:
count = int(f.read())
f.close()
channel = self.bot.get_channel(903918973408665620)
channel.send("{count}")
myLoop.start()
@commands.command(name="name")
async def name(self,ctx, name=None):
channel = int(968972997031506002)
channel2 = self.bot.get_channel(channel)
await channel2.edit(name=f"{name}")
def setup(bot):
bot.add_cog(Commands(bot))```
thats my entire code for the cog
just normal import discord 😄
yeah
bot is already defined so why is it saying it isnt
but which library
Raptzz probs
Why are you using int() on an integer?
discord.py doesn't have ApplicationContext
To be safe ig lol
hmm i didnt import no others.. (sorry i prolly sound dead stupid - but im rlly new with python 😂 )
wut
focus on the issue pls
It's already 100% going to be an integer
because thats just placeholder
show the full error
there were a few problems b4 that i cldnt thigure out.. but it seemed to work regardless those 😅
It was a joke -.-
show me crypto, the function part
await msg.add_reaction(":enemy_yes:")
``` i did this wrong didnt i
perhaps, try using the emoji object
not the reaction part but the emoji part
Perhaps 🤨
@bot.slash_command(guild_ids=[956267961751044146], description="We've all heard of it, but what does it actually mean?")
async def crypto(ctx):
embed = discord.Embed(
title='Cryptocurrency',
description="[text block]",
colour=discord.Colour.blue()
)
embed.set_footer(text='For anything else, just use the /help command.')
embed.set_author(name='Night Wolf', icon_url='[link.jpg]')
embed.add_field(name='Getting Started:', value='[How crypto actually works →]([link.jpg] \"Watch here\") [How to get started with Crypto →]([link.jpg] \"Read More\")',
inline=True)
embed.add_field(name='Also Try:', value='!crypto-mining, !blockchain, !bitcoin, !investing, !buy-crypto', inline=False)
embed.set_image(url='[link.jpg]')
i replaced all the links
example
py-cord?
if u wouldnt mind
idek i legit just imported discord 😅
emoji = discord.utils.get(bot.emojis, name='emoji-name')
await msg.add_reaction(emoji)
try ctx.respond
In 2.0 how can I make a specific / command to only one server
Check for guild or cogs ig
add a check
ayee tysm, it works now! 😄 also, only if ur not busy atm xD i still get these random errors tho they dont seem to be affectin anything 
and what type of command? message command? text command? slash command? user command?
are you making raw requests to the API?
wdym? 😅
Clearly he isn’t
Hey, I'm trying to get a program to send a webhook. I've tried searching for solutions but they all use a module called "discord-webhook" and when i try to use it, it says no module named "discord_webhook" exists
maybe it's an internal bug, try asking in the py-cord server if you haven't already
just like this?
import discord
import requests
data = requests.post('https://discord.com/api/v10/')
bot = discord.Bot()```
you forgot to install it
no, that was just an example
i did install it though, im trying now to install it with pip3 and not pip
aah dang, im rlly clueless 😂
show me how you installed it
did you restart your IDE?
where can i find the api for it? 😅
api for what?
messages don't have titles.. nor descriptions
uugh idek im lost now. oh wait, na, u were askin if im usin requests to api, i thought u said i "should" do that 😂 sorry mb
👍
so now that ik im not 😄 do u know what can b causing those errors? 😄
@client.event
async def on_message(message):
results = collection_prefix.find({"guild_id": message.guild.id})
for result in results:
pass
if result["prefix"] == "":
client.command_prefix = dprefix
await client.process_commands(message)
else:
client.command_prefix = result["prefix"]
await client.process_commands(message)
hello im currently trying to do a custom guild prefix and im having issues to check if the value guild_id is none and when its none it should insert the guild into the database
when i try to use the variable result it says local variable 'result' referenced before assignment because the list is empty
Looks like something internal, i don't really know
alright, thx anyways for your help! 😉
How do I splice up the text so it does not flood the chat, such as multiple pages? When I have tried this in the past it has crashed.
accidental reply 
why are you passing in the for loop?
lads, shld i just stick with slash cmmnds or add prefix commands as well? xD
thats for the list so i can do like result["field"]
both
cool.. but python doesn't like that, move the if/else statement into the loop
howd i go bout doin so 😅 do i needa do two completely seperate commands?
depends, if you're using py-cord yes, if you're using discord.py no
aah, with discord.py how? 😅
!d discord.ext.commands.hybrid_command new feature
@discord.ext.commands.hybrid_command(name=..., **attrs)```
A decorator that transforms a function into a [`HybridCommand`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.HybridCommand "discord.ext.commands.HybridCommand").
A hybrid command is one that functions both as a regular [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
and one that is also a [`app_commands.Command`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.app_commands.Command "discord.app_commands.Command")...
that was not my problem my problem is that it searches for a field called guild_id and then the value the guild id and if it doesnt find the value current guild id it throws an error and i want to handle that error
thx
check if results is None..
doesnt work
well it should work
In my bots DB I'm storing a channel ID for where I want my bot to greet members, a message I want members to be greeted with and a Boolean for if the guild has member greetings enabled. My original plan for doing this was so that admins could toggle if they want greetings enabled or not without erasing their greeting message or their greeting channel however I have since realized I could remove the Boolean and remove the greeting channel and just run a check on if the channel exists or not as the deciding factor for if the greeting message gets sent, what do you guys think; should I keep or remove the Boolean
when i try to print results
<pymongo.cursor.Cursor object at 0x000002726CEF7610>
maybe i should try find_one
i think thats the error
okay
keep
yeah that was the problem
okay guess I'm keeping it,
didn't you already make it connect to a VC in your code?
I'm getting this from a discord.py hybrid command, not really sure why. Anyone know?
ServerDisconnectedError: Server disconnected
I can send the whole error if it would help, but it gets to the end of the command, until a ctx.send() at the end.
how do I turn of view message history?
Lock is easy but I cant find the overwrite for it
yes send it
This is consistently happening btw
https://paste.ofcode.org/h9gS9QDYUZJacBwvh2kqwP
Restarted bot, discord, synced commands, etc.
How to make the bot be a speaker when connecting to the channel
seems like the aiohttp session got disconnected
indeed
weird i see no reason why it would
nah that really shouldnt be an issue
bro you see how i said really
chill out

your bot has to request to become a speaker https://discordpy.readthedocs.io/en/master/api.html?highlight=request#discord.Member.request_to_speak
do you make requests inside of resize?
Thanks you
@flat solstice And if the bot is a moderator of the stage channel, can he enter and become a speaker himself?
I think the bot has to request to speak regardless, but I've never played around with stage channels so I don't know
Got it
ahhh thanks sifte
when i try to edit a channel name this happens despite it having manage channel permission;
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
but when it has administrator it works? why can't it edit channel names with the manage channel perm?
overwrite.read_messages_history isnt working
I'm guessing the Manage Events permission in the Discord application configurator isn't for bot.event(), but rather actual "events" in a discord server?
👌
Discord Developer Portal
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
go to the oath section of your bot
you need to configure a default invite
o: ?
inside oath its called "general"
yer
import discord
from discord.ext import bridge, commands
import os
from dotenv import load_dotenv
# Secrets
load_dotenv("secrets.env")
TOKEN = os.getenv("DISCORD_TOKEN")
PREFIX = os.getenv("DISCORD_PREFIX")
# Intents
intents = discord.Intents.default()
intents.message_content = True
# Initialize
bot = bridge.Bot(intents=intents, command_prefix=PREFIX)
# Commands
@bot.bridge_command()
async def reply(ctx: bridge.context.BridgeContext):
await ctx.reply("Hello!")
@bot.bridge_command()
async def reply2(ctx: bridge.context.BridgeContext):
await ctx.reply("Hi!")
# Run
bot.run(TOKEN)
My second slash command won't appear in the slash commands menu when I type /. The first one works fine, but the second one doesn't. (I'm using PyCord 2.0.0 btw). The prefixed version works, but the slash command version doesn't...
? ye
if you synced globally it will takeup to hour to show up
I have to sync?
does pycord to it for you?
working, thanks!
👍
IDK
But adding specific guild_id(s) to the decorator worked
I just wanted to do it without that
it will take an hour to sync then
Right, thanks
how do I get the voice channel that the bot is in?
ctx.bot.voice.channel doesn't work
nvm it's ctx.voice_client.channel.members
!d discord.VoiceClient.channel
The voice channel connected to.
thanks but my thing works fine
unless it's like super intensive? it checks how many people are in it each second
will that impact performance at all?
or should I just use events to check when members change
that returns all the members in the voice channel
oh wait sorry I mistyped
I wanted the voice channel that the bot was in in order to get the members
it's ctx.voice_client.channel I meant
https://github.com/albertopoljak/Licensy
I want to change this bots excisting commands into slash commands is it possible can someone help through it/
is it possible
yes
can someone help through it/
can't you do that yourself?
I need some help brother can't do thiss all alone
Hi back
Hello, I have a question. I've been trying to read the docs for Guild.audit_logs(). and im still having trouble. How would I get this to see if the past two logs and see if the two logs were channels being deleted? ```py
@bot.event
async def on_guild_channel_delete(cha):
async for entry in cha.guild.audit_logs(limit=2, action=discord.AuditLogAction.channel_delete):
print("2")
the event gets called when a channel gets deleted
why do you wanna check again
Warning (from warnings module):
File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\cogs\api.py", line 28
start_loop()
RuntimeWarning: coroutine 'DiscordListsPost.start_loop' was never awaited``` ```py
async def start_loop():
await self.api.start_loop()
await DiscordListsPost.start_loop()
print("Post Count")
start_loop()``` how can i fix this?
await start_loop
so ```py
async def start_loop():
await self.api.start_loop()
print("Post Count")
await start_loop()```
When do u need to start it
when the code starts
Is it in a cog?
yes
Override cog_load as a async function and start it there
sorry i do not know how to
Within the cog class
so ```py
async def cog_load(self):
await self.api.start_loop()
print("Post Count")
cog_load()```
ok
Also you might have to use self.bot.loop.create_task
i get this ```py
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\echo.py", line 53, in <module>
asyncio.run(main())
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\echo.py", line 46, in main
await bot.load_extension('cogs.api')
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 869, in load_extension
await self._load_from_module_spec(spec, name)
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 808, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.api' raised an error: AttributeError: ('loop attribute cannot be accessed in non-async contexts. ', 'Consider using either an asynchronous main function and passing it to asyncio.run or ', 'using asynchronous initialisation hooks such as Client.setup_hook')```
Huh then looks like I was wrong
so now what?
Not sure. Hopefully someone else can come along
ok
anyone know what style of docstrings disnake uses
I think numpy
I also had something like that earlier
I just circumvented by manually grabbing the event loop and using that instead of the loop attr for Bot
asyncio.get_running_loop().create_task()
You can either put in the cogs init
Or the cog_load method
you can look into the src simply
and its ofcourse same as discord.py ones which uses sphinx autodoc
wym
sending a message will always need an await or are there exceptions?
Anything calling the API basically needs to be awaited
😳 unless you make requests to the API manually using requests
will there ever be certain exceptions?
been there done that..
Probably
nope, all of them are api calls
There might be a few edge cases, but nothing to send messages
nah, anything which makes a request to the API is an awaitable in discord.py since they use aiohttp and its all async
@bot.event
async def on_guild_channel_delete(cha):
async for entry in cha.guild.audit_logs(limit=2, action=discord.AuditLogAction.channel_delete):
print("2") ``` how would i get this to grab the last two logs and see if they were channel_delete? ``nvm i solved my own question``
How can I pause what the bot is playing in voice channel?
Pause your voice client
Yeah i know
I did and it's numpy style docstring but weird
man no ones answering 😔
It's like 95% numpy and 5% something else
Which i can't find what this mixed style numpy is
Sphinx's docstring looks weird
apparently thats what you use if you want your packages to be automatically documented by sphinx
what
edited
Does anyone know why this just sends the same image that was sent to the command, except it also doesn't load? The size is the same, too.
https://paste.ofcode.org/4Wk2VBxbDQzRqKjaDaR2dT
!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.
you aren't awaiting the coro and recursion
??
?
I do not get what you mean because I do not remember seeing anything like that in the original code
what
Exactly what I said I do not remember seeing anything on the lines of coro and recursion not even exactly 100% sure what that is
#normal function
def say():
print("say whaat")
#coroutine
async def say():
print("I'm a coro")
how can i add a check to a interaction w discord components
you must offer more details to us to help you
Okay so i'm doing a thing with buttons but i only want the author of the person that invoked the command to be able to use the buttons not everyone
in a wait_for?
do you mean remove all the embeds from a message?, and for the bot's message?
like
suppose someone sends a message which embeds something (like a link)
i wanna collapse the embed
usually you would use Message.edit(embeds=[]) but i doubt if that would work for other user's message
It won't
You can't edit other people's messages like that (thankfully)
Depending on how complex your bot is atm it would be easier to just add an if statement at the start of the command callback
There are probably modules out here that add check functionality though. Discord recently added a nice permission update for slash commands as well
Although idk if the libraries added support for it yet. Idek when the update was
!d discord.Message.edit
await edit(content=..., embed=..., embeds=..., attachments=..., suppress=False, delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the message.
The content must be able to be transformed into a string via `str(content)`...
would that work with messages sent by others tho?
If the bot has manage_messages permissions, yes
alr dope thanks
Surprised they haven't made a separate method to prevent confusion
How to send files?
await ctx.send(file=discord.File('yourfile'))
can someone elp me setup slash commands
Traceback (most recent call last):
File "C:\Users\beege\Documents\GitHub\EconomyDiscordBot\main.py", line 16, in <module>
tree = app_commands.CommandTree(bot)
File "C:\Users\beege\Documents\GitHub\EconomyDiscordBot\venv\Desktop\Coding\lib\site-packages\discord\app_commands\tree.py", line 131, in __init__
raise ClientException('This client already has an associated command tree.')
discord.errors.ClientException: This client already has an associated command tree.
Not sure why this is happening
can someone please help me with a help command for my bot?
you don't need the tree variable, you can use bot.tree
@bot.slash_command(name = "help", description = "Help command for the bot")
async def help(ctx):
embed = disnake.Embed(title = ' help', description = 'Help command for alaska bot' )
for command in bot.walk_commands():
description = command.description
if not description or description is None or description == "":
description = 'No Description Provided'
embed.add_field(name = f"``{command.name}{command.signature if command.signature is not None else ''}``", value = description)
await ctx.send(embed = embed) ```
would this work for help command
try it and see
slash commands?
my bot is online but its not sending any message and not showing any error in the console wht to do ?
it has admin perms
yes
did you sync the commands?
how do i do that?
do you want this to be global or only for one guild
global
yes
global
it's supposed to do that if you only run your bot?
Then you have to wait 1~ hour for them to register
@boreal ravine fyi that website is blacklisted because its often used in an unfriendly way
yes the bot is online
👌
Permissions update I've told you about just came out officially
Are you running a command?
yes
- Does your bot have the message content intent?
- Do you have an
on_messageevent?
discord library version?
oh alright ty, but only 2 of my commands are showing up is that normal or-
3
3? 💀
what's wrong?
Do I have to sync the slash commands?
Yes
Just for my guild
No
idk\
perhaps
me need put "not" to elif?
if you dig deep enough into danny's secret folders
what are these riddles
rayden somehow got access to it 💀
elif not mutedRole in member.role:
My English is very bad
@boreal ravine how do I sync the commands just for my guild
I don't want to have to wait hours
lmao sift did you send the don't ask to ask
!d discord.app_commands.Tree.sync
python bot is kinda weak in looking for discord.py docs 😔
Separate command
how
its just harder than using readthedocs imo
Nope, I sent https://uwu.uwu 
docs are harder to use for me
mostly because they won't load
😔

risky click of the day
same
ah sry its 3.8
💀
u asked py version right ?
They meant your discord.py version
python = "^3.6"
where error?
How do you add the command to the tree?
How do you reference the command when adding it I mean
you don't.. doing ```py
await bot.tree.sync()
automatically syncs all of your bots application commands
Hey @zenith mural!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
How would I format a slash command in a cog?
https://paste.pythondiscord.com/oqurecexus whenever i implement slash commands to this it doesnt work
can someone help?

I'm off to bed, but if anyone would like to just dm me the way to setup a slash command in a cog that would be sick
@slash.slash(
name = "Register-Steam-Friend-Code",
guild_ids = guilds
)
async def registerFriendCode(ctx: SlashContext, code: str):
author = ctx.author
savedFriendCodes[ctx.author_id] = code
verificationRole = get(ctx.guild.roles, id = verificationRoleID)
await author.add_roles(verificationRole)
await ctx.send("Your Steam friend code is now registered.")
client.run(token)
- discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
Why does it say I am missing permissions? I invited my bot with admin permissions and also used applications.commands
To be more specific the Missing Permissions is pertaining to await author.add_roles(verificationRole)
the bots top role is below the authors top role
or maybe it doesn't have permissions
it was because the bots top role was ranked lowest
I did not know the order mattered
How do you pull a random image from an online gallery, namely https://fluffart.cheddr.dev/ ?
I figured out how to get it from a subreddit, but I'm not really sure what path to take from here
are you using a webscraping method?
I used something similar to that for the reddit part, but no, I am not sure where to begin with that
btw you can't get images from that site if there isn't API
images are get from a script which connects to a relative path inner the website
Oh I see, do you happen to have any links to some kind of documentation for how to do that?
Actually, I should probably look that up before asking - sorry!
No you didn't understand i'm not talkin of a script to get the images i'm talkin about a javascript inside that page that retrieves images somewhere else and there isn't a link to them
Ah, gotcha
Can we get the time when the command was used like i am using mysql for afk command and i want to show that x user was afk x seconds ago
<t:7272773:R>
Is this form
messages have a created_at paramater
Yeah but i want that int in unix time
!d discord.Message.created_at
property created_at```
The message’s creation time in UTC.
it doesn't tell the type, btw it give you a datetime object
you can manipulate it however you want
@bot.slash_command(name = "whois", description = "shares a users info")
async def whois(ctx, user : disnake.Member = None):
if user== None:
user = ctx.author
rlist = []
for role in user.roles:
if role.name!= "@everyone":
rlist.append(role.mention)
b = ','.join(rlist)
embed = disnake.Embed(colour = user.colour, timestamp= ctx.message.created_at)
embed.set_author(name = f"User Info: {user}"),
embed.set_thumbnail( url = user.avatar.url),
embed.set_footer(text = f"Requested By: {ctx.author}",
icon_url = ctx.author.avatar_url)
embed.add_field(name = 'ID', value = user.id, inline = False)
embed.add_field(name = "Joined At: ", value = user.display_name, inline = False)
embed.add_field(name = "Created At: ", value = user.created_at, inline = False)
embed.add_field(name = "Joined At: ", value = user.joined_at, inline = False)
embed.add_field(name = f"Roles: ({len(rlist)}))", value = ''.join([b]), inline = False)
embed.add_field(name = "Top Role: ", value = user.top_role.mention, inline = False)
embed.add_field(name = 'Bot?', value = user.bot, inline = False)
await ctx.send(embed = embed)
``` can someone please help me with this whois command it isnt working
slash commands in disnake takes up to 1 hour to be registered globally. Please read the docs
why is this not wrking
Traceback (most recent call last):
File "main.py", line 165, in <module>
@client.command()
AttributeError: 'Client' object has no attribute 'command'
@client.command()
async def ping(ctx):
await ctx.reply(f"My API Latency is {round(client.latency * 1000)}ms")
show your client instance
oh alr ty, will read them
*on discord
thats for all libraries, not specific to disnake
you need to use commands.Bot instead of discord.Client to make commands
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result
anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with
this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality
to manage commands...
What's this supposed to mean? ```py
Ignoring exception in on_connect
Traceback (most recent call last):
File "/home/runner/Modmail-Bot/venv/lib/python3.8/site-packages/discord/client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "/home/runner/Modmail-Bot/venv/lib/python3.8/site-packages/discord/bot.py", line 1025, in on_connect
await self.sync_commands()
File "/home/runner/Modmail-Bot/venv/lib/python3.8/site-packages/discord/bot.py", line 685, in sync_commands
await self.http.bulk_upsert_command_permissions(self.user.id, guild_id, guild_cmd_perms)
File "/home/runner/Modmail-Bot/venv/lib/python3.8/site-packages/discord/http.py", line 357, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 405 Method Not Allowed (error code: 0): 405: Method Not Allowed
I'm in a server with a bot that has a neat pop up dialog box, does anyone know what this is called? Here's how it looks on mobile
its a "modal"
Form
its a Form, referred to as a Modal
!d discord.ui.Modal
class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.
This object must be inherited to create a modal popup window within discord.
New in version 2.0.
Examples...
Ty everyone!
hi so ik with a module i could do Embeds.no_perms
but i want to add dots like Embeds.no_perms.perm_level_2
like more dots
dots
You could subclass discord.Embed
like?
What the
That's not how you subclass
Also why are you subclassing object
uh
idk
can you give me an article
ive tried looking
for some
thanks
Corey Schafer has some nice videos about OOP
class MyEmbed(discord.Embed):
my_property = "this"
``` smthing like this
Good intentions but bad naming convention 🥲
im making a multiguild bot, am i best using MongoDB or MySQL fo sorting all the data? im using MongoDB atm
What would you need that static field for
More like #databases question
just asked in there cheers
Well wait for the answer there?
eyy?
wouldnt matter
by default classes subclass the object class
you need to actually subclass it yourself in py2 iirc
that was just a reference to how to subclass a particular object since they were doing it wrong
the my_property thing yeah, that isn't needed
Ok
class variable is the term
Afaik both terms are ok
Everytime i look at your avatar i think of the sims
😳
well its typehinted as var: ClassVar[type] = ...
Everytime i look at urs, i imagine a duck smoking...
Why smoking
Why not a sexy duck
😳
😳
everytime i look at urs i imagine brocolli
.... 

Everytime i see yours it's a flaming octopus

Squidward with tiny bumps
bro
thats pretty cool
burn octopus
sure, but they all have a different meaning
Static is like "accessible with class without creating an object" and class var is specifically a static variable of a class
static also means that the variable cannot be changed, but in python it can be changed
It doesn't mean that
well isnt static mean its in the global scope?
Most of languages have final modifier
no, those are constants
correct
what it?
ah ye, mb
reset your token
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
and yeah youre missing intents hence why your AbstractEventLoop stopped
there is an error in the line with the token
in <module>
Waht error
@slate swan yeah reset your token
I just now saw
Look up, there's more than one error there
Can someone help me with my code?
the custom exceptions say it all why dont people listen to them😔
i tried to make a custom prefix and when i finished i got this
fyi, you censored the public bit of the token and left exposed the bit that is actually private
https://paste.pythondiscord.com/perusomaja for this code i am trying to have the user to edit their bio. Can someone help me change it?
Isn't that what this server is about? Spare me the time and just ask 😅
they don't know what they mean, hence is why they asked
@minor totem
i`m reset
its quite easy to read a custom exception message? it literally gives a whole link as well
Bots don't have access to bios
While you're at the dashboard, can you now enable the intents you're trying to use? The message intent recently so that you need to enable in on the dashboard
You need to store the warning then, is that what you want help with?
Nope its not warn cmd its edit bio profile cmd where the user can edit their bio in their profile
Am trying to make like this
nope lol
bots can't see bios
You can't because bots can't get access to bios
Bota?
that's probably a Client object
thats probably just given
and even if they could, you can't someone elses bio
even with the regular discord client
its a api limitation so it really doesnt matter
now, if you created bios that are not the discord bios, like store them in a database and edit them, it might work
thats probably the case.
hey how can i see who someone replied to in my bot?
do you mean like a certain channel?
i mean like say i took that message you just sent
check message.reference
how can i see who it replied too

!d discord.Message.reference
The message that this message references. This is only applicable to messages of
type MessageType.pins_add, crossposted messages created by a
followed channel integration, or message replies.
New in version 1.5.
it returns None in some cases, so just use a check
ok ok
Well this is for my dating server and some servers are allowed to edit their bio ive seen that
i am talking about biograpghy no bios thing that your talking about
What're you getting stuck with?
they probably copy the users discord bio, add it to a db and allow the user to edit the db bio
No
Can i dm you?
About me's can't be that long
and explain
okay, then it's probably a separate bio entirely on the db
How to use on_message inside cogs? discord.Cog.listener? If so, do I do: @commands.Cog.listener()?
yes
@commands.Cog.listener('on_message')
async def on_message(self, message: discord.Message):
...```
yeah one provided by the user
Why the ('on_message')?
optional
sometimes you have to define the event with a string
but required if the method name isn't an event

like if you had multiple listeners for the same event
but lets be real, no insane barbarian would use multiple on_message events.
A new discord.py user and it's forks would do use them
yeah but that was a given
File "c:\Users\thoma\OneDrive\Things\Documents\discord server bot\Bot2.py", line 6, in <module>
from discord.ext import commands
ImportError: cannot import name 'commands' from 'discord.ext' (unknown location)```
nvm i figured it out
nope i have not
please help
Resolved
@client.command(name="setup")
async def setup(ctx):
await ctx.send("Starting setup! What does the name of invite channel needs to be?")
msg = await client.wait_for("message")
await ctx.send(f"Channel named {msg} made")
``` How do I fix this so whenever someone like types test as the channel name it will say Channed named test
I changed the code but this gives a weird response too
the check you had earlier was close: py def check(m): return m.content == "" and m.channel == ctx.channel you just need to tweak the return statement so the content doesnt have to be empty, and you might want to make sure the message comes from the same author too
I mean I don't want anything in the string, I just want people to like name their own channel
well thats the problem, m.content == "" means someone has to send an empty message to pass the check, e.g. by uploading an image
Hm, how would I then do what I am trying to do?
Then you need to create your own system that stores that
flip the condition around to != or simply write m.content and ... so the check can allow messages with at least one letter
@client.command(name="setup")
async def setup(ctx):
await ctx.send("Starting setup! What does the name of invite channel needs to be?")
member = ctx.author
def check(m):
return m.content != "" and m.channel == ctx.channel
msg = await client.wait_for("message", msg.author == member)
await ctx.send(f"Channel named {msg} made")
``` Do you mean this?
yeah close, just move that author condition in the check
the wait for returns a Message object so to access their actual text afterwards you'd use msg.content, printing {msg} directly is what gives you a "weird response"
ahh
It's giving me this error
return m.content != "" and m.channel == ctx.channel
``` Should that be instead of m msg
no nvm
you want to have that author condition handled in your check too
multiple listeners is a pretty good way to separate different systems, e.g. my mod cog has one to detect outside invites and another for dealing with particular spam messages
one equals sign is called an "assignment", two equals signs is an "equality comparison" which would be the condition im referring to
Erm so which one?
the one with two equals signs...
Yeah sorry
np
Apparently pystyle dosent work in my console for some reason. I use pydroid 3
Getting this rn
yeah you need to correct the variable you're using after you put it in your check
notice how the previous conditions m.content != "" and m.channel == ctx.channel use m for the message (given in your check parameters)
i would assume at the end of that line is where you pasted msg.author == member
You mean m.author then?
yes
async def setup(ctx, m):
``` Do I define m here too
nah, you only need to check the author inside the check so someone else or a bot can't interfere with the command
Hi sup
hi sparky
@client.command(name="setup")
async def setup(ctx):
await ctx.send("Starting setup! What does the name of invite channel needs to be?")
member = ctx.author
def check(m):
return m.content != "" and m.channel == ctx.channel
msg.author == member
msg = await client.wait_for("message", m.author == member)
await ctx.send(f"Channel named {msg.content} made")
``` so this should just work?
It says that m is not defined tho
you're still doing the comparison outside of the check, and also not passing the check function to wait_for
Hi
!resources
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 the bot receives a message it goes into the check function and if it returns True, the wait_for returns the gotten message, you need to define the function correctly
@bot.slash_command(name = "whois", description = "shares a users info")
async def whois(ctx, user : disnake.Member = None):
if user== None:
user = ctx.author
rlist = []
for role in user.roles:
if role.name!= "@everyone":
rlist.append(role.mention)
b = ','.join(rlist)
embed = disnake.Embed(colour = user.colour, timestamp= ctx.message.created_at)
embed.set_author(name = f"User Info: {user}"),
embed.set_thumbnail( url = user.avatar.url),
embed.set_footer(text = f"Requested By: {ctx.author}",
icon_url = ctx.author.avatar_url)
embed.add_field(name = 'ID', value = user.id, inline = False)
embed.add_field(name = "Joined At: ", value = user.display_name, inline = False)
embed.add_field(name = "Created At: ", value = user.created_at, inline = False)
embed.add_field(name = "Joined At: ", value = user.joined_at, inline = False)
embed.add_field(name = f"Roles: ({len(rlist)}))", value = ''.join([b]), inline = False)
embed.add_field(name = "Top Role: ", value = user.top_role.mention, inline = False)
embed.add_field(name = 'Bot?', value = user.bot, inline = False)
await ctx.send(embed = embed)
``` its been over 3 hours since i coded this and its still not shown up in my bots slash commands, could someone please help me?
Is your application authorised with application.commands scope
yeah it is
This disnake?
yeah its disnake
there's a couple examples in the docs if you want to reference those again
https://discordpy.readthedocs.io/en/stable/api.html#discord.Client.wait_for ```py
def check(m):
# == comparisons stay in here
return m.content == 'hello' and m.channel == channel
msg = await client.wait_for('message', check=check)
^ include this too```
Try to parse a list with your guild id to test_guilds kwarg of bot constructor
bot = commands.Bot(..., test_guilds=[12345])```
Yeah
I don't know if the commands will still be registered for non test guilds
Yes it is a simple list
@bot.slash_commmand(name = 'mute', desrciption = 'Mutes The Specified User')
@commands.has_permissions(manage_messages = True)
async def mute(ctx, member: disnake.Member, *, reason = None):
guild = ctx.guild
mutedRole = disnake.utils.get(guild.roles, name = "muted", case_insensitive = True )
if not mutedRole:
mutedRole = await guild.create_role(name = "muted")
for channel in guild.channels:
await channel.set_permissions(mutedRole, speak = False, send_messages = False, read_message_history = True, read_messages = True)
await member.add_roles(mutedRole, reason = reason)
await ctx.send(f'Muted {member.mention} for {reason}')
await member.send(f'You were muted in the server {guild.name} for {reason}')
``` btw im getting an error with this mute command, mind helping me?
ill show you the error hold up
why not just timeout
How do you define bot
I never did non cog implementation in disnake so not sure if that decorator exists but I have a suspect that it does
bot = commands.Bot(command_prefix = ",", test_guilds= [my test guilds]
Yes it won't
oh
How do you import commands
from disnake.ext import commands
lol
!d disnake.ext.commands.Bot.slash_command
@slash_command(*args, **kwargs)```
A shortcut decorator that invokes [`slash_command()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.slash_command "disnake.ext.commands.slash_command") and adds it to
the internal command list.
This thing exists
what is this
Basically what you did
alr nvm
I don't know why you receive AttributeError
How?
Ah
Well I am bad at explaining stuff in english 😩
The check=check
its a kwarg in wait_for
bot = commands.Bot(...)
@bot.slash_command(...)
async def cmd(...)```
I kinda confused you sorry
@bot.slash_commmand(name = 'mute', desrciption = 'Mutes The Specified User')
that instead of this?
You made a typo
3 "m"s
My bot is online but not responding how can i fix this ??
That's why lmao
wdym 3 m's
I agree
You typed commmand instead of command
oh LMAO
That's why it's not working
Could you share your code if it's not very big
its big
!paste
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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Just make sure to remove the token
@vale wing so now the command will take 1 hour to get updated?
or ill just send the important stuff ? ill remove the cmnds frm middle as there is no mistake there
If you have test guilds it will immediately update in them but it won't update in other guilds until you remove the test guilds
Sure
i removed the test guilds
ig ill add them to test first
I suspect you have issues with on_message, could you send it here @stiff gorge
Oh god
Use pasting service pls
ok
Imagine God also helpless lmao
Might be prefixes issue
Lol
i hv saved it here
Read the bottom text of that embed
You clearly didn't read anything and just went to link
Ah yes
is it possible to stop certain servers using specific commands? i know ill be able to run it in a if linked with a database but not sure if there was an easier way?
!pypi keep_alive
Lmaooo this also exists
from flask import Flask
from threading import Thread
app = Flask('')
@app.route('/')
def main():
return "Your bot is alive!"
def run():
app.run(host="0.0.0.0", port=8080)
def keep_alive():
server = Thread(target=run)
server.start()
Yea
!d discord.ext.commands.Bot.check
@check```
A decorator that adds a global check to the bot.
A global check is similar to a [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is applied
on a per command basis except it is run before any command checks
have been verified and applies to every command the bot has...
cheers
@stiff gorge I have found a lot of weird stuff in your code so um do you receive your on_ready print
yes
And it doesn't respond to commands?
no
@stiff gorge do u have an event deco?
Do you have
@bot.event
async def on_message(...)```
Somewhere in your extensions?
i removed all extension still it dosent respond
extensions can only have listeners
@commands.Cog.listener()
async def on_message(self, mes):
...```
i had updated to the latest py version today
dpy version or python version?
oh wait you got disnake huh
i had updated to py 2.0 but the bot was showing many errors so i made it to dyp
so you're using dpy 2.0?
yes
you need to enable the message content intent in that case
intents = discord.Intents.default()
intents.message_content = True
😳 self,
okay that too
when i change it to this this error occurs
Traceback (most recent call last):
File "main.py", line 30, in <module>
intents.message_content = True
AttributeError: 'Intents' object has no attribute 'message_content'
yo anyone worked with hybrid commands?
Code
because: discord.py 2.0 has changed Member.avatar_url to Member.avatar.url
and it would be ideal to use display_avatar since avatar sometimes may return None (if the profile picture is discord's default)
no
Use disnake
Hi sparky
Hi 👋
How are u?
anyone? 😅
which library?
sheesh, they released Hybrid cmds so early
Why
😄 wld u know your way around em? i got as far as doin slash commands but struggling to do prefix commands as well for same command
# example in a cog
@commands.hybrid_command() # this will create a global slash command 'ping' and a message command 'ping'
async def ping(self, ctx):
await ctx.send("pong")
here's a short example
What do you mean doesn't work
what do i import 😅 ive only imported discord for now.. 😕




