#discord-bots
1 messages · Page 949 of 1
you can compare integers too
I thought it return the id in weird var type
@astral fossil bro I meant command name
the command function name open is overriding the in built function named open
It probably from discord modules
......?
so, I want to make a command where it searches for messages in a channel with a certain keyword.
Would the best thing for this to be inserting the messages into a DB? It's just for one server
well u can use channel.history but it is gonna be slow asf
I cant find it
w h a t
Ima tried running the code on other device
Bro
If it worked on other device im burning this raspberry pi
yeah so database is more efficient but i'm thinking a good way to make sure only the wanted messages are there
Okay I hate my writing now
with an on_message? Sure
What the heck do u think I wrote here

and the colour choice
It worked
Idk when I selected it and I cba to change it
yes
Nice thx
huh?
Possibly thanking for someone else
lmao
Imagine pinging randoms
they are helpers
check their roles
Bro they are all volunteers
oo
Its not like they are getting paid or smth to help u
Post yr code and problem
i am just learning
i wanna know how can i make a bot join a vc when the code is run
without any commands
!d discord.VoiceChannel.connect
await connect(*, timeout=60.0, reconnect=True, cls=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Connects to voice and creates a [`VoiceClient`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceClient "discord.VoiceClient") to establish your connection to the voice server.
This requires [`voice_states`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.voice_states "discord.Intents.voice_states").
async def join_vc(ctx):
channel="959704295903748137"
await client.join_voice_channel(channel)
No
?
channel = client.get_channel(id-here)
await channel.connect()
let me try
also id is int
its fine, everyone starts from somewhere
@client.event
async def on_ready():
print("bot online") #will print "bot online" in the console when the bot is online
async def join_vc(ctx):
channel = client.get_channel(959704295903748137)
await channel.connect()
didnt join the vc
;-;
lol
is client a commands.Bot instance?
bad
then u can tell him, go on
client = discord.Client()
client = commands.Bot(command_prefix = '!')
what if the id is of a text channel
its not
lmao
ahem ahem
lemme check ;-;
lmao
oh wait wrong reply
and you shouldnt define client twice
okay its a vc
i just picked the default discord.py code from repl.it ;-;
dont-
client = commands.Bot(command_prefix = '!'), discord.Client()
import discord
import os
import time
import discord.ext
from discord.utils import get
from discord.ext import commands, tasks
from discord.ext.commands import has_permissions, CheckFailure, check
client = commands.Bot(command_prefix = '!'), discord.Client()
@client.event
async def on_ready():
print("bot online")
async def join_vc(ctx):
channel = client.get_channel(959704295903748137)
await channel.connect()
@client.command()
async def ping(ctx):
await ctx.send("pong!")
async def kick(ctx, member : discord.Member):
try:
await member.kick(reason=None)
await ctx.send("kicked "+member.mention)
except:
await ctx.send("bot does not have the kick members permission!")
client.run(os.getenv("token"))
!code thanks
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
...?
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!", intents=discord.Intents.default())
@bot.event
async def on_ready():
print("online uwu")
@bot.command()
async def join(ctx):
channel = bot.get_channel(channel_id)
if not channel:
return
try:
channel.connect()
except discord.Forbidden:
return await ctx.send("missing access")
bot.run(token)
this is how it should look like
lemme try
You gave them the code
and you need PyNaCl for VCs
lmao
just do pip install discord.py[voice] and u r done
It's like throw stake to a bunch of lions and telling them not to devour it
who is a lion here now Indeed
Also i was mostly expecting you to name bot to uwu
Don't make her remember that its already annoying
oh... wrong channel
main.py:18: RuntimeWarning: coroutine 'Connectable.connect' was never awaited
channel.connect()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Await it
await channel.connect
It's a coroutine
import pip
def install(package: str):
if hasattr(pip, 'main'): return pip.main(['install', package])
return pip._internal.main(['install', package])
try:
import Module
except ModuleNotFoundError:
install("package")
so uwu
and what is Module here
Ignoring exception in command join:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 18, in join
await channel.connect()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/abc.py", line 1150, in connect
voice = cls(client, self)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/voice_client.py", line 199, in __init__
raise RuntimeError("PyNaCl library needed in order to use voice")
RuntimeError: PyNaCl library needed in order to use voice
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 902, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 864, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: RuntimeError: PyNaCl library needed in order to use voice
;-;
the package you wanna import uh
Ah gotcha
bruh python is hard
pip install discord.py[voice] in yr command prompt
c was easy
Well Python uses C under the hood
@maiden fable what can i do about it?
;-;
I told u
^^^
Also there is a discord wrapper in C too, in case u want to check it out
doesnt work
Nvm there isn't one
lmao
You know, it will work with people who have common sense
@maiden fable sir its working but i wanted so that it joins when the code is turned on so that i dont have to type a command
use on_ready
Well
?
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!", intents=discord.Intents.default())
@bot.event
async def on_ready():
print("online uwu")
channel = bot.get_channel(channel_id)
if not channel:
return
try:
channel.connect()
except discord.Forbidden:
print("Gimme perms")
bot.run(token)
sir, dont
discord[voice] to be exact.
bet
ic
why?
same
np i am on a vm

because that event is triggered multiple times and has a higher chance of your bot disconnecting
like how many times is it triggered?
its different huh
as much as it wants
wydm?
help bug: ```py
IMPORT FISOCRD
CLITNETE = FISOCORD.FICOCORDO(CLIENT=NONE, CPREFIX="UWU*)
CLIEGNENE.RUN("UWU.GOKEN")
dont shit on uwu smh
whats fiscord?
...
okay but whats it?
what is that github
..
DNS error
Looks sus as hell
FREE NITRO
Hmmm

TRUST.
:)
yea
download download
i dont trust humans
There, did
lol
btw @maiden fable so with that code if i will run the code for 24/7, so the bot will be in the vc forever??
Meh, even if u get my IP and get my laptop name, idgaf its named as HP anyways and brave has blocked all the website trackers
ic
U cannot get my location anyways 🤷
me on dark web ;-;
Stop, its against ToS
uwu
spam bot??
When i say hi it spams hi back
How do I fix
Btw it is under an a message event
Spams?
How many times
Replace pass with return
Ok
Hello Ash
and is it good to define a variable every message....?
Hey Skev
Did it stop repeating itself
It sending it twice
@slate swan this you
It’s sending it twice
hi guys are you interested to host your bot for free ? I have a youtube video that is really helpful and I get it, my bot is hosted without paying anything, of course you can pay to upgrade some characteristics but that's not important
Advertising?
no just help
That's what someone who is advertising would say
imagine if a guy here looking for hosting his bot
im not promoting anything
Nvm
You are promoting your video
that's not my bruh
🗿
~~ advertisements all the way down~~
bruuh
You're still promoting a video
ok so we can't help here
It doesn't matter if it isn't yours
🤦♂️
No you can if it's actually relevant to someone's problem
You literally just posted that out of the blue
and is it forbidden ? I can't see anything that forbid it
!rule 6

maybe advertising is forbidden but help each other...
did I posted the link of the video ? man your cringe
"unapproved"
That's still advertisment even if you didn't post a video link
lmao
The member.bot is not working it’s responding to a bot
First of all why do you have the if statement indented in the other if statement
And why are using member.bot
It's in a on_message event
You don't have member
What do I use then?
It's message.author.bot iirc
Also remove the if statement from the other one
Ok
Also why are you comparing the message author's id to a bot property
Idk
It should just be
if message.author.bot:
return
Actually he's right
is this correct usage?
async def on_message(self, message):
if message.channel.id != CHANNEL_ID or \
not message.author.bot or \
not message.attachments:
return
Sure, but u dont need \
then what can I put?
U can instead do:
if (
condition1 or
condition2
or condition3
):
I just showed u 2 ways to put or
Either at the first or last
@discord.ext.commands.has_role(959430769086959646)
async def mute(ctx, member: discord.Member, *, reason=None):
guild = ctx.guil
mutedRole = discord.utils.get(guild.roles, name="Muted")
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=False)
await member.add_roles(mutedRole, reason=reason)
await ctx.send(f"Muted {member.mention} for reason {reason}")
await member.send(f"You were muted in the server {guild.name} for reason {reason}")```
File "main.py", line 75
await member.add_roles(mutedRole, reason=reason)
^
IndentationError: unindent does not match any outer indentation level
how to fix?
oh my
If you're just starting with python, and aim to program a discord bot, I suggest first going over python and getting a basic understanding of it.
There are some helpful guides in the link below
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
it just had some writing errors
Have you fixed them?
ah okay cool
Is this bot just for testing/one server?
Because the way you're making the muted role if there is no role named Muted isn't very efficient.
one server
im making a bot for my own server.
when making the unmute command
and i cant find the problem in that
@discord.ext.commands.has_role(959430769086959646)
async def unmute(ctx, member: discord.Member):
mutedRole = discord.utils.get(ctx.guild_roles, name= "Muted")
await member.remove_roles(mutedRole)
await ctx.send(f"Unmuted {mention.member}", delete_after = 20)
await member.send(f"You were unmuted in the server {guild.name}")```
File "main.py", line 84
await member.remove_roles(mutedRole)
IndentationError: unindent does not match any outer indentation level
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
how to fix it
do you know what indents are?
this as a reference would help
which editor or IDE are you using?
replit
can you paste your code in the link below and save it and send the url
!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 copy-paste
@client.command(description = "Unmutes the specified person")
@discord.ext.commands.has_role(959430769086959646)
async def unmute(ctx, member: discord.Member):
mutedRole = discord.utils.get(ctx.guild.roles, name="Muted")
await member.remove_roles(mutedRole)
await ctx.send(f"Unmuted {mention.member}", delete_after = 10)
await member.send(f"You were unmuted in the server {guild.name}")
this is a function, so all the code for the command should be indented a tab after the async def unmute(ctx, member : disnake.Member):
and your decorators are wrong
!d discord.ext.commands.has_role
@discord.ext.commands.has_role(item)```
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 invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
and I must mention your unban command is a very bad practice
Tbh, missing the check if the member is already muted
tis not my code
yeah it's probably from a YT video
it is im just making my first bot i wanna have some features
and learn at same time
I would personally advice against such videos as they generally do not provide good code. Even though it works, it's not good code
You are free to ask here, we can help you with that
But i need an working unmute command now
your error is regarding indents, i already told you, put the command code inside the function
But maybe you should learn basics of Python if you have indentation problems
In Python without indentation you can't do nothing
well you can
😔
!e
print("uwu")
@slate swan :white_check_mark: Your eval job has completed with return code 0.
uwu
yeah that's what I wanted to say rn
You can print uwu world
good enough
how do you get the number of reactions the message has in a raw_reaction_add?
U need to fetch the message
Fetch the message and check the reactions using len(message.reactions)
there was some undocumented bot._connection.get_message or something
import discord
from discord.ext import commands
from datetime import datetime
class Yawncommands(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.Cog.listener()
async def on_member_join(self, member: discord.Member):
channel = self.bot.get_channel(915295833845530656)
if not channel:
return
wel_msg = discord.Embed(title=f"Welcome {member}!", description=f"Greetings {ctx.member.metion}. Thank you for joining us, please follow the rules and check out our patch notes and announcements for updates on the server. ", colour=0x9b59b6, timestamp=datetime.utcnow())
wel_msg.set_footer(text="supposedIy_sam", icon_url="https://i.imgur.com/8re0BwN.png")
wel_msg.set_thumbnail(url="https://i.imgur.com/8re0BwN.png")
await channel.send(embed=wel_msg)
def setup(bot: commands.Bot):
bot.add_cog(Yawncommands(bot)
NameError: name 'ctx' is not defined
It's member.mention
Why would you use ctx?
It's in a on_member_join
Making an api call every reaction yikes
hi
Ig you're swastiking
??
are you copying a video
No not rn
What is the error
No error
When I type ?bal @jaunty folio it says my bal
Instead of @jaunty folio bal
you always use ctx.author
?
You hard coded the user to be the author
idk u tell me
Hehe
Wdym
and you opened the account of yourself, not the user
Oh
would bot.get_message be not good?
So what do I do
this is why you don't just copy a video without understanding
It can be, but u gotta increase the cache size
Remove that line, and you'll have user be equal to the tag (or the author of no tag/id was given with the command)
how do I do that?
If you need the author somewhere else, use ctx.author or add author = ctx.auhtor somewhere instead of using user again
Since that will override the variable you used in the command before
pretty sure you have to replace ctx.author in the open_account() aswell
also where are the docs for bot.get_message?
can u even understand what he is trying to make
@formal basin do open_account(user)
Yes, you'll have to do user there as well
I don't think that exists
does it
!d discord.RawReactionActionEvent
class discord.RawReactionActionEvent```
Represents the payload for a [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") or [`on_raw_reaction_remove()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_remove "discord.on_raw_reaction_remove") event.
Still showing my bal
what did u state when calling cmd
it only has a message_id
?bal @jaunty folio
You're still using ctx.auhtor instead of user when making the embed
pretty sure you have to fetch the message
I assume if you check the numbers it will be their bal :)
Oh
So ctx.user?
no
user variable that you made use it
use it
god
No need to use ctx
Do I use that
Ok
user is already the person
or display_name
It works
You should only use ctx if you need some info from the command you used (the msg, the author, ...)
Thanks
idk u tell me why u put that stuff in ur formatted string
@discord.ext.commands.has_role(959430769086959646)
async def mute(ctx, member: discord.Member, *, reason=None):
guild = ctx.guild
mutedRole = discord.utils.get(guild_roles, name="Muted")
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 {reason}", delete_after = 10)
await member.send(f"You were muted in the server {guild.name} for reason {reason}")
i havent changed the code i think
what lib u use
discord.py master
It doesn't say Successfully muted anywhere?
tag?
You can always just use <@id> to tag
i know
What I meant was, the msg in your screenshot is no where in the code you send
use timeout instead
iirc it's the max_messages kwarg
though increasing the cache size will make your program use more ram
but if a have a lot of ram then go for it
i dont like the discord timeout
I need To get all channels of bot is in not for one guild for whole how do i get it anyone pls go through and help
Now my mute command dosent work
Traceback (most recent call last):
File "/home/runner/Bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/Bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/Bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'guild_roles' is not defined
!d discord.ext.commands.Bot.get_all_channels
for ... in get_all_channels()```
A generator that retrieves every [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel") the client can ‘access’.
This is equivalent to:
```py
for guild in client.guilds:
for channel in guild.channels:
yield channel
``` Note
Just because you receive a [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel") does not mean that you can communicate in said channel. [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for") should be used for that.
@discord.ext.commands.has_role(959430769086959646)
async def mute(ctx, member: discord.Member, *, reason=None):
guild = ctx.guild
mutedRole = discord.utils.get(guild_roles, name="Muted")
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=False)
await member.add_roles(mutedRole,reason=reason)
await ctx.send(f"Muted {member.mention} for reason {reason}", delete_after = 10)
await member.send(f"You were muted in the server {guild.name} for reason {reason}")```
So would i use , client.get_all_text_channels()? @honest shoal
if you have your bot defined as client, yes
ok I try If any error i will get back to you
how can i make a command to snipe an edited message with discord.py
like, how to get the original msg
it isn't working @honest shoal
what you did?
possible with on_message_delete event
@client.command() async def testt(ctx): r, g, b = tuple(int(x * 255) for x in colorsys.hsv_to_rgb(random.random(), 1, 1)) embed=discord.Embed(color = discord.Color((r << 16) + (g << 8) + b), timestamp=ctx.message.created_at) all = len(set(client.get.all_text_channels())) embed.add_field(name="Bot Channels: ", value=all) await ctx.send(embed=embed)
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
I use?
yes
!code @client.command()
async def testt(ctx):
r, g, b = tuple(int(x * 255) for x in colorsys.hsv_to_rgb(random.random(), 1, 1))
embed=discord.Embed(color = discord.Color((r << 16) + (g << 8) + b), timestamp=ctx.message.created_at)
all = len(set(client.get.all_text_channels()))
embed.add_field(name="Bot Channels: ", value=all)
await ctx.send(embed=embed)
ahh
?
@client.command()
async def testt(ctx):
r, g, b = tuple(int(x * 255) for x in colorsys.hsv_to_rgb(random.random(), 1, 1))
embed=discord.Embed(color = discord.Color((r << 16) + (g << 8) + b), timestamp=ctx.message.created_at)
all = len(set(client.get.all_text_channels()))
embed.add_field(name="Bot Channels: ", value=all)
await ctx.send(embed=embed)```
just posting from your side to make it readable
this is not how it works
use a for loop
I didn't understand
did you get any error
Where are the docs for max_messages kwarg for bot
Internals
``raise CommandInvokeError(exc) from exc
2022-04-02T10:53:27.972087+00:00 app[worker.1]: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'get'``
Oh hmm i thought it'd start with _
The documentation exists in discord.Client's paremeter
You want all text channels for all guilds?
Why?
I want to mention it in bot info
Pls help
whats the issue?
From that specific guild?
Yeah Like When I Do Botinfo The Bot sends the number of text channels he has the access
It isn't working see up
That's for messages that get deleted
all_channels = len((await ctx.guild.fetch_channels()))
num_of_channels = len([guild.text_channels for guild in bot.guilds])
this will return the number of text channels the bot has access to, maybe
the message deleted can be stored with that
Ok i try both
He wants to snipe edited messages
Oh he means all, still this will be a nested list so won't work.
🗿
ohh, I didn't read properly
yeah just figured out
!d discord.Client.get_all_channels
for ... in get_all_channels()```
A generator that retrieves every [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel") the client can ‘access’.
This is equivalent to:
```py
for guild in client.guilds:
for channel in guild.channels:
yield channel
``` Note
Just because you receive a [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel") does not mean that you can communicate in said channel. [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for") should be used for that.
my bad
easier
for an edited message?
no
all_channels = len([channel for guild in bot.guilds for channel in guild.text_channels])
``` try this
yeah i was asking for how to get the original message from an edited one
c = ([channel in guild.text_channels for guild in bot.guilds])
what would this do?
@cloud dawn
channel is undefined
i think it would create a list of every text channel of every server the bot is in
This will say channel isn't defined at first.
ic
That First?
@slate swan double for loop
yea i saw
Yep.
y? its like a for loop, iterating through the list guild.text_channels and assigning the temporary value its on to the channel var
Still it would return a bool since in is used at the beginning.
And in bot.guilds will give a syntax error.
oh
Might as well use bot.get_all_channels instead
tru
But he wanted text channels.
isinstance exists
Would be more code and not faster since this is the get_all_channels function ```py
for guild in client.guilds:
for channel in guild.channels:
yield channel
Not working
Do you got an error? Share current code.
@client.command()
async def testt(ctx):
r, g, b = tuple(int(x * 255) for x in colorsys.hsv_to_rgb(random.random(), 1, 1))
embed=discord.Embed(color = discord.Color((r << 16) + (g << 8) + b), timestamp=ctx.message.created_at)
all_channels = len([channel for guild in bot.guilds for channel in guild.text_channels])
embed.add_field(name="Bot Channels: ", value=f"{all_channels}")
await ctx.send(embed=embed)```
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Command' object has no attribute 'guilds'
@cloud dawn this is the error
You have a command named "bot"
Huh, get_all_channels is a generator?
No
This is equivalent to: might have to look at the source rn
Wait nvm, yea it is. Just use list(get_all_channels) then, ig?
Ouh
Then channels = len(cnl for cnl in bot.get_all_channels() if isinstance(cnl, TextChannel)) should work
The error says so
Still a generator ```py
def get_all_channels(self) -> Generator[GuildChannel, None, None]:
"""A generator that retrieves every :class:.abc.GuildChannel the client can 'access'.
This is equivalent to: ::
for guild in client.guilds:
for channel in guild.channels:
yield channel
.. note::
Just because you receive a :class:.abc.GuildChannel does not mean that
you can communicate in said channel. :meth:.abc.GuildChannel.permissions_for should
be used for that.
Yields
------
:class:.abc.GuildChannel
A channel the client can 'access'.
"""
for guild in self.guilds:
yield from guild.channels
Does Mee6 bot allow other bots to use their commands?
No
Hm

This is just as long as mine but slower.
It is?
I mean you are getting more results then filtering them using isinstance so I'd say it is.
What i do now?
Still the same error?
Yeah
try this ```py
@client.command()
async def testt(ctx):
r, g, b = tuple(int(x * 255) for x in colorsys.hsv_to_rgb(random.random(), 1, 1))
embed=discord.Embed(color = discord.Color((r << 16) + (g << 8) + b), timestamp=ctx.message.created_at)
all_channels = len([channel for guild in client.guilds for channel in guild.text_channels])
embed.add_field(name="Bot Channels: ", value=all_channels)
await ctx.send(embed=embed)
Its working but i have a question
Does that was because of f string?
No that's because it looked weird with an f-string
the main issue that since I thought we were making a command I used bot but since you named bot client and not bot, I used bot instead of client but generally with commands we use bot for better naming.
this is annoying me
If you're getting all channels, get_all_channels() will be faster as it's using yield from keyword
The file name that is called Admin.py starting with an uppercase?
yes
Why
whats wrong with it being uppercase
Panda never said there was something wrong with it starting with a uppercase
wdym by why then
Traceback (most recent call last):
File "C:\Users\Micro\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 113, in wrapped
ret = await coro(arg)
File "C:\Users\Micro\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 783, in _invoke
await self.callback(ctx, **kwargs)
File "c:\Users\Micro\Downloads\Canomi\main.py", line 51, in serverinfo
await ctx.send(embed = embed)
File "C:\Users\Micro\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\abc.py", line 1438, in send
data = await state.http.send_message(
File "C:\Users\Micro\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 357, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.fields.4.value: Must be 1024 or fewer in length.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Micro\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 994, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\Micro\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 314, in invoke
await injected(ctx)
File "C:\Users\Micro\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 119, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.commands.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.fields.4.value: Must be 1024 or fewer in length.
``` whats this error mean
for the code of
@client.slash_command(guild_ids = servers, name="serverinfo")
async def serverinfo(ctx):
all_roles = ""
for role in ctx.guild.roles:
all_roles += f"{role.mention} "
guild = ctx.guild
embed = discord.Embed(title = ctx.guild.name, description = f"Information on {ctx.guild}", color = client.ecolor)
embed.add_field(name = "Members", value = guild.member_count, inline = False)
embed.add_field(name = "Channels", value = f"All channels: {len(guild.channels)} \n Text Chanels: {len(guild.text_channels)} \n Voice Channels: {len(guild.voice_channels)}", inline = False)
embed.add_field(name = "ID", value = guild.id, inline = False)
embed.add_field(name = "Owner", value = guild.owner, inline = False)
embed.add_field(name = f"Roles ({len(guild.roles)})", value = all_roles, inline = False)
embed.set_thumbnail(url = ctx.guild.icon.url)
await ctx.send(embed = embed)
It means field 4 roles is too big to send for Discord.
o
You can check for char length and cut items.
I don't think bot_count is a thing, you might have to iterate through every member instead and see if they're a bot, to then add them to a list.
Also, ideally don't ghost ping; it's just not cool for some people.
how can i count tho
there has to be some way!
Add to a list
iterate through guild.members check if the member is a bot
int += 1
What's a function for bot to list (mention) all users that have a specific role?
Trying to create a staff list bot.
Why not mention the role instead of mentioning all users?
Trying to create a staff list bot.
so...
for every member
if your role in their roles
add to list
user_mentions = [member.mention for member in role.members]
This takes more processing.
Or that, that seems like an excellent and neat solution
It's been a while since I've done bot development.
Is there a way I can make a command so you can choose your staff roles, and then it uses those for this command / event that will auto-edit itself whenever someone new is being added to one of those roles
@cloud dawn
!d discord.on_member_update Yes that is possible
discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") updates their profile.
This is called when one or more of the following things change:
• nickname
• roles
• pending...
Likely not
where should i store bot db cursor?
i have bot.db which is the connection
bot.cursor = bot.db.cursor()?
mhm
Is there an example of how to use it, on this code for example?
@bot.command(pass_context=True)
async def getuser(ctx, role: discord.Role):
role = discord.utils.get(ctx.message.server.roles, name="mod")
if role is None:
await bot.say('There is no "mod" role on this server!')
return
empty = True
for member in ctx.message.server.members:
if role in member.roles:
await bot.say("{0.name}: {0.id}".format(member))
empty = False
if empty:
await bot.say("Nobody has the role {}".format(role.mention))```
ty
its an event
fyi pass context is on by default
oh jeez, it's that long ago.
This is not equivalent of what you want to do, you also need an event.
And yeah the code is very old
@bot.event
async def on_member_update(before, after):
...
Okay, let me try.
bot.say 🗿
pass_context isn't even a kwarg anymore.
^
Wait what
role = discord.utils.get(ctx.message.server.roles, name="mod")
if role is None:
But what if you don’t want context
Should I use this line?
on message commands.
What if you make it false
Better to use IDs but sure
Hm I guess you can just use a placeholder variable _
It will be public later on,
but trying to test if it works as private bot first.
Gotcha, probably best to have a command that sets the mod role
Sadge
Then you most likely need to save that channel id and make them assign a role.
So your users aren’t forced into a certain name for their mod roles
(Hint: database time!)
Yeah, I need to work on it ah. The role(s)*
Aka pretty much work lol.
Using a name or id will both be hard-coding.
Have some time to help me out, lol?
I know.
That's why am I trying to find an other way.
And all the sources seems old as fuck.
im trying to learn aiosqlite but im getting no where
Robin always has time, he once made a whole system for someone. You're in good hands.
Even on phone.
A little bit, on mobile so can’t really provide code snippets like I normally would like to
I gotta say I don’t remember
But glad you think that 😊
in the first parenthesis, you specify the column to insert to
Mind messaging you? We can work later on when you get a bit more time.
If you don't mind- 😐
js api flashbacks
dw ptsd will kick in after a year or so
Feel free to open up a help channel anytime and ping me and maybe Panda if they wanna help
Help channels are generally better since people can pop in and provide some feedback
I want to help.. but I'm going soon so don't want to ty myself to a big thing rn. My grandpa is having his birthday :)
The thing is I don't know where to start from, including the set mod roles command.
No prob, wish him happy birthday for me 🎉
Tell him i said happy birthday to him
🥳 👍
Oh that’s easy. Just a regular command that takes a role as an argument
By typehinting to discord.Role
Wish him happy birthday
I know what he want to make... it's a bit more work than that.
If they don't respond i can also try to help
Thanks bud.
So basically a set argument command?
Ping CokeCane (go ahead, laugh) if you open up a help channel later
Basically yes, for your testing phase just save it into a bot var or something, in production it should be saved onto a database
@modern fiber okay correct me if I'm wrong.
He want to create a static channel dedicated to a staff list.
That when someone gets added or deleted to update itself.
So looking at dynamic input of role and channel and saving the msg id.
slightly
Hello, I need to add the pfp of the user for my userinfo command, not the authors pfp
Not being sarcastic, it shouldn’t be very difficult to code if you know what you’re doing, that is
This requires combining like 10+ methods and a database.
user.avatar.url
ctx doesn't have an avatar.
When you put it like that maybe
it would be user.avatar.url in your case
embed.set_thumbnail(url=member.avatar_url)
Yes, kind of.
The person will be able to use /setup command and choosing the mod roles, and staff list channel.
So after it, it will mention the people that have these roles from the highest to lowest mod role, and then after it updates itself whenever the staff list updates. Or could've set it like every 5 days or something.
More so about time than difficulty
member = ctx.message.author
Instantly is better, every 5 days would require even more coding.
Oh okay, then instantly.
Not what he wants
Is there an event dispatched for on role update?
We already answered
Tough you do need some kind of buffer since people.
user is already a parameter of his function. no need
@client.command(aliases=["whois"])
async def userinfo(ctx, member: discord.Member = None):
if not member:
member = ctx.message.author
roles = [role for role in member.roles]
embed = discord.Embed(colour=discord.Colour.purple(), timestamp=ctx.message.created_at,
title=f"User Info - {member}")
embed.set_thumbnail(url=member.avatar_url)
embed.set_footer(text=f"Requested by {ctx.author}")
embed.add_field(name="ID:", value=member.id)
embed.add_field(name="Display Name:", value=member.display_name)
embed.add_field(name="Created Account On:", value=member.created_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"))
embed.add_field(name="Joined Server On:", value=member.joined_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"))
embed.add_field(name="Roles:", value="".join([role.mention for role in roles]))
embed.add_field(name="Highest Role:", value=member.top_role.mention)
print(member.top_role.mention)
await ctx.send(embed=embed)
on_member_update
Or is that part of on guild update
.
Hm. Okay you can use that to update the staff list
Yeah,
No that did not work
Or is that what you’re already doing? I saw some mention about on member update a while ago
Hmm you do need some kind of buffer if people quickly add/remove roles since rate limit lol
Yeah let’s get an MVP out first then worth about that haha
However, I have not even 1 line of code, and not sure where to start, nor I can find any source than this shit that is old like a decade
https://stackoverflow.com/questions/52025872/python-get-all-members-list-from-a-specific-role
Public bots are a pain to debug.
Do you have a git?
Do you have a basic bot set up?
Yep.
Question what library do you use to connect to the discord API?
Could you share, it's easier to work that way.
The intents and other?
Nextcord
Sure, hold on.
Yes, and just a basic ping command or something
Yeah i don't use that i don't know if they have something different
Best place to start is a basic bot structure
Could make a PR I'm bored sometimes anyways.
Never made a PR before
The GitHub has a basic_bot.py example that might be useful to you
Would also want to try
I do, let me just how to add a code to a GIT, pretty new to GIT ngl.
Takes a bit to get the hang of but you’ll get there
Do recommend learning it since it is pretty handy when someone wants to help you.
Yes.
No
Oh not an app-
It seems impossible for me to install app since I get like 50 errors.
desktop is awesome
help please it counts each letter of a string
Where?
I find the desktop to be intimidating
Lol.
]
Follow the first commands
can someone help it counts each letter of the string and tries putting it in db
"echo "# Staff-List" >> README.md
git init
git add README.md
git commit -m "first commit"
git branch -M main
git remote add origin https://github.com/LAV12354sjuddd/Staff-List.git
git push -u origin main"
I recommend github desktop unless you like no-gui command line harcore windows user like robin
I don’t even use windows man
😳
In the terminal, not here haha
😳
LOL
git desktop can be launched on xp
It’s good. You’re not the first one
bruh my vps is almost faster.
LMFAO
you dont have git installed it seems
on my desktop?
Should be an easy fix
or should I use pip install git
LMFAO
We're not linux where we download programs trough cl
You’ll need git a lot so Better to have it than not
sudo pacman -S git is easier than all this clicking around
Ignore my rondo all turca mp4
mhmhmh maby i like the clicky sounds
imagine using MacOS
Or you know, coming pre installed like a normal person 🙃
There you are
You’re learning!
Switch them.
Yep
Hm?
who reads release notes lol
True
So I should uncheck it and check git bash?
Check it off if you want doesn’t matter
Yes
Yeah close that off
Closed it
There is your GUI-less command line interface.
Now you can follow those commands git told you about
Mk.
These ones
Just the first section
Instead of git add README.md do git add .
I recommend logging in first.
Oh come on
Huh?
Does git auto add to path on windows?
When you spam next so you forgot to add it to PATH lol
.
Damnnit
Fine we’ll do this manually
gitdesktop
😳
Go on your GitHub repo and it should be a button to upload files
We were already doing that with this cl lol
Gits being a pain
"…or import code from another repository
You can initialize this repository with code from a Subversion, Mercurial, or TFS project."
This one?
Hllo
Did you press the <> code button?
reading https://strftime.org, how do i have hour as a decimal if it says invalid
Ola
Yeah..
1.5
hm?
Right
Pressed it..
Oh lmao no you need to add 30 min with time.
huh
i just want the hour number non-zero padded
Lol, okay.
No, no don't stop mid way.
Git is a pain to install
LOL, well thank you at least for helping me 😂
not really
theres an installer, and then you restart
as long as its added to path then ur good
Sorry couldn’t do more. Usually gits pre installed for me
Which I don’t think it is
I mean git desktop is pretty easy
theres an option when setting it up
i use github desktop personally and it installs it while you install desktop so
@modern fiber or you can run the installed this time and instead of spamming next look for a “add to path button” and check it
Would basically need a command like this to start off with, @sick birch
and its nice to have a gui
👍 🙏
ok let me uninstall this one lol
Have you registered a slash command for it?
Not yet.
That’s a good place to start
I was kidding, you need bash the cl you made him click away
Damnit
this might be what i need
Pandabweer this one’s for you
Dark mode please.. my eyes
not racist u are panda
GitHub desktop… my bane
Just click on publish repo to get started lol
wait i dont want month i want hour
What next
MMM, i both black and white so i got both powers.
lol
Click on show in explorer and move the project files there then hit commit.
Make sure to not include your token
oh pycharm..
.
I recommend pushing it trough pycharm then otherwise issues and pycharm will get a heart attack.
.
I heard too much unknown things today
my brain is stopping to function
Then head over to the git desk again then you should see the local changes.
You'll get the hang of it, i did it solo. It did took 2 hours to setup git and modify some things.
Okay
Okay sup,
Panda helped me a lot with making the git.
@sick birch https://github.com/lavoxarslan123/cool
Next up will prob be the .env so you won't need to think about leaking the token again lol
Thanks for the source.
Appreciate it.
how do i turn a big float into a small float kinda thing
like turn 52.538520052078596 into 52.5
@client.command()
async def add(ctx, a:int, b:int):
embed=discord.Embed()
embed.add_field(name="Solution", value=(a+b))
await ctx.reply(embed=embed)```
!e ```py
print(round(52.538520052078596, 1))
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
52.5
ah ty
!d round
round(number[, ndigits])```
Return *number* rounded to *ndigits* precision after the decimal point. If *ndigits* is omitted or is `None`, it returns the nearest integer to its input.
For the built-in types supporting [`round()`](https://docs.python.org/3/library/functions.html#round "round"), values are rounded to the closest multiple of 10 to the power minus *ndigits*; if two multiples are equally close, rounding is done toward the even choice (so, for example, both `round(0.5)` and `round(-0.5)` are `0`, and `round(1.5)` is `2`). Any integer value is valid for *ndigits* (positive, zero, or negative). The return value is an integer if *ndigits* is omitted or `None`. Otherwise, the return value has the same type as *number*.
For a general Python object `number`, `round` delegates to `number.__round__`.
bro can we split the terms
ah
like when i use add i give command -add 1 2 i want that it should be 1+2
@cloud dawn?
Aren't you getting that?
Or as result you want 1+2=3 back?
as result only answer but when i give command it should be like 1+2
hmm what if you wanna add more than 2 nums?
thats more of not a very helpful command imo
no offence
Look into commands.Greedy
its considered as int so what do you think?
I know how but it's very hard coded, command will get pretty big to account for all peoples mistakes.
I don't like greedy
greedy also dies with 1+1+1+1
For calc it's best to just eval it and return the result.
why wouldnt eval work?
bro but asking for help is not so called greedy
wait what....
ignore
!calc await bot.logout yes use eval
I'll just go lmao
!d discord.ext.commands.Greedy
class discord.ext.commands.Greedy```
A special converter that greedily consumes arguments until it can’t. As a consequence of this behaviour, most input errors are silently discarded, since it is used as an indicator of when to stop parsing.
When a parser error is met the greedy converter stops converting, undoes the internal string parsing routine, and continues parsing regularly.
For example, in the following code:
```py
@commands.command()
async def test(ctx, numbers: Greedy[int], reason: str):
await ctx.send("numbers: {}, reason: {}".format(numbers, reason))
``` An invocation of `[p]test 1 2 3 4 5 6 hello` would pass `numbers` with `[1, 2, 3, 4, 5, 6]` and `reason` with `hello`...
bot wouldn't be defined.
Using eval directly hooked up to a bot?
huh
Bad idea
Cant people run anything there
I think it's marvelous.
Then !calc exit()
Like if someone put in exit(), i think the bot would shut down
What are the odds haha
4/10
Also i think it might be possible for them to do print(token) and guess the environ you stored token as and get ur token
take a shot every time i said token
If its is a calc command just make a parser which parses the string which contains the mathematical expression
won't be too hard 
now that is a scary emoji
"won't be too hard"
yeah
no comments
only 3?
late realization lmao
the understood was sarcastic...
lmao
just clone it using git (if in pycharm) or just clone the repo in replit
U hosting the bot on yr pc?
Install pypresence and use discord yo change/update ur custom presence
Idk, just a better way to update presence 🤷♂️
Nah, for yr profile
Nvm, u don't understand what I mean lol
I have used pypresence before, isnt there a better way to get rich presence instead of that? ping me in #ot2-never-nester’s-nightmare if you do know 😔
I mean, pypresence isn't bad tbh as long as u don't look at the source code
thats why and it needs to be ran as a background task on the same device
I have worked with its source code and uhhhh, I don't have words to explain how beautiful it was
wont ask
There is no other way tho
pfftt
Blame discord, not pypresence
@client.command()
async def test(ctx):
discord_embed = discord.Embed(
title="Testing Select Menu",
components=[Select(
placeholder='Select something',
options=[
SelectOption(label="Option 1", value='1'),
SelectOption(label="Option 2", value='2'),
SelectOption(label="Option 3", value='3'),
SelectOption(label="Option 4", value='4'),
],
custom_id='SelectTesting')])
await ctx.send(embed=discord_embed)
interaction = await client.wait_for(
'select_option',
check=lambda inter: inter.custom_id == 'SelectTesting' and inter.user == inter.author)
res=interaction.values[0]```
Guys I am working on making a dropdown/select menu in discord
The code I wrote is not sending the drop down menu and is only sending an embed with the title in (Line 4 ). Can someone please help me fix this
Only a title is being sent
How do i define date here:
now = date.today()
Can someone help me out in this please
Traceback (most recent call last):
File "C:\Users\ryuga\AppData\Roaming\Python\Python310\site-packages\discord\ui\view.py", line 373, in _scheduled_task
await item.callback(interaction)
File "E:\Computer Science\Python\Game\Discord\Oxygen\cogs\wiki.py", line 290, in go_to_sections
await interaction.response.edit_message(embed=self.cls.wiki['about'], view=self.cls)
File "C:\Users\ryuga\AppData\Roaming\Python\Python310\site-packages\discord\interactions.py", line 658, in edit_message
await adapter.create_interaction_response(
File "C:\Users\ryuga\AppData\Roaming\Python\Python310\site-packages\discord\webhook\async_.py", line 194, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.url: Not a well formed URL.
this is an example url self.wiki[val] generates
https://upload.wikimedia.org/wikipedia/commons/thumb/a/a8/Bill_Gates_2017_%28cropped%29.jpg/220px-Bill_Gates_2017_%28cropped%29.jpg
it was working file, few mins ago 
Hey ryuga!
👋🏻
Could you have a look at the problem I am having please
Its working fine but Its only sending the embed with the title and not the dropdown menu
This
hmmm, use the discord.ui.Select select, its much better
Do I import that?
yea if u have d.py 2.0+
How can I check the version
I think I have above 2.0
Pretty sure
@paper sluice Could you tell me where I shd put it in the code
Is there a possibility that sometimes it's None?
there is but i have handled that, the url i send is the only url im sending for testing
what r u putting?
Try printing the url everytime
The discord.ui.select?
you can't have above 2.0 since not even 2.0 it's officially released
i did, its the same, it works fine with normal embeds, idk why its creating problems with select meues
`message`
u can git clone it
you can git 2.0 but there's no above 2.0
and 2.0 it's not even stable so meh
ya sure. mb
Ok but where do I put it in my code after importing?
umm wait
This is the Ultimate Python Guide on Select Menus with Discord.py or Pycord. In this video, I talk about how to create select menus in discord.py or pycord and how to respond to dropdown menu interactions. After watching this you'll know everything about Select Menus in discord.py or pycord.
Ultimate Guide on Buttons: https://youtu.be/kNUuYEWG...
gmt_time_zone = pytz.timezone('GMT')
is this incorrect?
Ok thanks!
for interactions, do y'all prefer bot.wait_for or a callback func?
callback func

