#discord-bots
1 messages · Page 560 of 1
^
SyntaxError: invalid syntax
File "<stdin>", line 1
line 1. This indicates your intepreter is fucked or something. restart your ide?
idk man its 1 and im doubting myself
it says invalid syntax, line 1. Unless you have a command on line one, just restart your ide
i sometimes get this on visual studio code
np
you can actually do bot._connection._get_message(message_id) ._connection returns ConnectionState object which has a _get_message() method
you might get "access to protected member" warning on some IDE tho
Say please what is iteration ?
iteration is looping through something
like @lament trail said, iteration is looping through things, such as lists.
example:
my_list = [1, 2, 3, 4]
for item in my_list:
if item == 3:
print("Found it.")
here i iterate through my_list which contains a list of ints
class discord.Guild```
Represents a Discord guild.
This is referred to as a “server” in the official Discord UI.
x == y Checks if two guilds are equal.
x != y Checks if two guilds are not equal.
hash(x) Returns the guild’s hash.
str(x) Returns the guild’s name.
property owner: Optional[discord.member.Member]```
The member that owns the guild.
it says it's a property
Cz it is....?
Isn't it the same damn thing....?
can i get help in #help-bagel
Sorry dude I gotta run rn
okay can someone help me get started with wait_for
Fixed my semaphore ratelimiter
bru what
!d discord.Client.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
ohh i was using Bot
Thanks!!
👍
okay i have the check part down but now how do i get the message
jsut set a variable to self.bot.wait_for("message")
Yes
The rules and guidelines that apply to this community can be found on our rules page. We expect all members of the community to have read and understood these.
!rule 8
8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.
not what i meant
we don't spoon feed is what i'm trying to say
do i have to put timeout = None?
@commands.command()
async def rnum(self, ctx):
await ctx.reply("please respond with 2 numbers for me to choose a random number from")
def check(reaction, user):
return user == ctx.author
l = await self.bot.wait_for("message",check=check,timeout= 10.0)
await ctx.send(l)
i prolly have to pass message right?
no cuz then
if user_message.lower() == '*specs':
embed = discord.Embed(title="Sunflower Duck's PC specs", url="https://www.youtube.com/watch?v=dQw4w9WgXcQ",
description="SSD: M.2 1000GB Hard Drive MOBO: B460M Pro Vdh Wifi GPU: Intel UHD 630 Case: H510 Elite RAM: 16GB CPU: Intel core i5 10400",
embed.add_field(name="Field 2 Title", value="It is inline with Field 3", inline=True,
embed.add_field(name="Field 3 Title", value="It is inline with Field 2", inline=True,
color=0xFF5733)
await message.channel.send(embed=embed)
return
I need help, it says wrong spacing area
you can just have a message object as an argument in the check func
message:discord.Message
?
Can u please use commands
!d discord.ext.commands.command
@discord.ext.commands.command(name=..., cls=..., **attrs)```
A decorator that transforms a function into a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or if called with [`group()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.group "discord.ext.commands.group"), [`Group`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group").
By default the `help` attribute is received automatically from the docstring of the function and is cleaned up with the use of `inspect.cleandoc`. If the docstring is `bytes`, then it is decoded into [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") using utf-8 encoding.
All checks added using the [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") & co. decorators are added into the function. There is no way to supply your own checks through this decorator.
How would you guys go on about making an if statement that checks if two emoji are the same
this is what I have rn to add an emote to the database
@client.command()
async def emoteAdd(ctx, name, emote):
if name in db.keys():
await ctx.message.channel.send("{0} is already an emote".format(name))
return
else:
db[name] = emote
so I used %emoteAdd fight \⚔️
Then I use this to send a message with a reaction
@client.command()
async def explore(ctx):
if check_survivor(ctx) == True:
e = discord.Embed()
e.title = "explore"
e.set_author(name = ctx.author.name)
e.set_image(url = "https://i.pinimg.com/originals/89/24/8b/89248bb8543b43bcb8958f0df9d8e8e5.png")
e.description = "You stumbled upon a building surrounded by zombies"
message = await ctx.channel.send(embed = e)
message_player[message.id] = ctx.author.id
toReact = ['⚔️', '🏃']
for x in toReact:
await message.add_reaction(x)
print(x)
replit db?
yep
then this to compare the emotes
@client.event
async def on_reaction_add(reaction, user):
if reaction.message.author == client.user:
print("The bot sent the message")
if reaction.message.id in list(message_player):
print("The message is in the list")
if message_player[reaction.message.id] == user.id:
print("The player owns this message")
print(reaction)
print(reaction.emoji)
if reaction.emoji == db["fight"]:
await reaction.message.channel.send("{0} chose to fight".format(user.name))
elif reaction.emoji == db["run"]:
await reaction.message.channel.send("{0} chose to run".format(user.name))
else:
await reaction.message.channel.send("{0} what you did is not an accepted action".format(user.name))
else:
await reaction.message.channel.send("{0} this is not for you".format(user.name))
My expected answer would be the user chose to fight
but this is the output
ehh okay
dont use a seperate reaction event for that , use wait_for
!d discord.ext.commands.Bot.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
@slate swan i need help with that btw
do i do async def rnum(self , ctx, message:discord.Message):
with the check? py def check(message): return condition
yes that part
i have def check(message, user):
return user == ctx.author
If I make a database using SQLite would I put it in cogs or?
you cannot have user as an argument
now what am i returning?
remove user and return message.author == ctx.author
okay
anywhere you want to
@commands.command()
async def rnum(self, ctx, message: discord.Message):
await ctx.reply("please respond with 2 numbers for me to choose a random number from")
def check(message):
message.author == ctx.author
l = await self.bot.wait_for("message",check=check,timeout= 10.0)
await ctx.send(l)
the part is message:discord.Message
obv but just asking if that is right
besides the message: discord.Message
!e print("Hello world!")
@modern path :white_check_mark: Your eval job has completed with return code 0.
Hello world!
does anyone know how to write code on discord? I really don't know :(
!e
def help():
print("test")
if name == "main":
help()
@slate swan :white_check_mark: Your eval job has completed with return code 0.
test
!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.
thx :D
Np!
i want to make a discord bot with a control panel, so what lib do you all recommend I use for it?
(im looking for a gui lib)
!d discord.Message it is
class discord.Message```
Represents a message from Discord.
x == y Checks if two messages are equal.
x != y Checks if two messages are not equal.
hash(x) Returns the message’s hash.
Huh, weird
After switching from client to using bot, the bug of repeating the greeting thrice is gone
pretty sure that the only changes I made was converting the whole thing to bot
Not really
alright then
Okay, not a bug
I had multiple different .py running, all containing the greeting sequence
I think
Me = dumb
That's a relief
how do i make the bot add a reaction every time a user sends a message after the "thread has been created"?
import discord
from discord.ext import commands
class test(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_message(self, message):
if str(message.channel.type) == "private":
if message.author == self.client.user:
return
else:
guild = self.client.get_guild(900458404953333808)
channels = await guild.fetch_channels()
channel = discord.utils.get(channels, name=str(message.author.name))
if channel is None:
category = discord.utils.get(guild.categories, name="Tickets")
channel = await guild.create_text_channel((message.author.name), category=category)
await message.author.send("thread has been created")
def setup(client):
client.add_cog(test(client))
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
would this be right https://hastebin.com/lafovixuru.py
How can I make a command to stop a command?
hey
dont use idiot api keys
use pywhatkit.playonyt
the the input
then it will play
type pip install pywhatkit
then you get that modue
then use
import pywhatkit
pywhatkit.playonyt("videonameorinput")
#This will play directly mmost relavent video on yt!
oh sorryyt
sorry for class
Task exception was never retrieved
future: <Task finished name='Task-1' coro=<SlashCommand.sync_all_commands() done, defined at C:\Users\jason\chad\venv\lib\site-packages\discord_slash\client.py:415> exception=HTTPException('400 Bad Request (error code: 30032): Maximum number of application commands reached (100).')>
Traceback (most recent call last):
File "C:\Users\jason\chad\venv\lib\site-packages\discord_slash\client.py", line 491, in sync_all_commands
raise ex
File "C:\Users\jason\chad\venv\lib\site-packages\discord_slash\client.py", line 471, in sync_all_commands
existing_cmds = await self.req.put_slash_commands(
File "C:\Users\jason\chad\venv\lib\site-packages\discord\http.py", line 254, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 30032): Maximum number of application commands reached (100).
WTF DOES THIS MEAN
no more slash cmds 😦
How can I put a cooldown on a slash command... Also it gives an error while using clean_content so i wanna fix tht
Which lib are you using
You can do
while True:
msg = await self.client.wait_for('message', check=check)
await msg.add_reaction("✅")
```If you want to add reaction to every message
on_guild_join
And what about leave
wait
Ok
discord.on_guild_remove(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild") is removed from the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").
This happens through, but not limited to, these circumstances...
@slate swan there
And join is what you said above
Yes
Ok thank you
how do i define check?
!d discord.on_guild_join
discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") joins a guild.
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
The same way you did but before the while loop
uhhh
this?
def check(m):
return m.content == message and m.channel == channel
@tough lance
ya
what does this mean?
import discord
from discord.ext import commands
from datetime import datetime
class command(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_message(self, message):
try:
if "*close" in message.content:
pass
else:
if str(message.channel.type) == "private":
return
else:
if message.author == self.client.user:
return
else:
user = message.guild.fetch_member(int(message.channel.name))
embed = discord.Embed(
title="message from mods",
description={message.content},
timestamp=datetime.utcnow()
)
await user.send(embed=embed)
except Exception as e:
print(e)
pass
@commands.command()
async def close(self, ctx):
user = ctx.guild.fetch_member(str(ctx.channel.name))
await user.send("your thread has been closed")
await ctx.channel.delete()
def setup(client):
client.add_cog(command(client))
I think it's cause you didn't fetch member correctly
is there a specific reason why you're using the channel name to fetch a member?
well anyway fetch_member fetches a member using the member's user id
so using the str(ctx.channel.name) wouldn't work
How can I get this information
on how many servers the bot is located on.
How many participants are from these servers in total.
And how many channels are there.
It also needs awaiting
bot.guilds, bot.users, bot.channels. Respectively
Code
@commands.command()
async def стат (self, ctx):
# main
servs = bot.guilds
users = bot.users
channels = bot.channels
print(servs)
error
Traceback (most recent call last):
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Baraban4ik\Desktop\Suzuki\cogs\info.py", line 96, in стат
servs = bot.guilds
AttributeError: module 'discord.ext.commands.bot' has no attribute 'guilds'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\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: AttributeError: module 'discord.ext.commands.bot' has no attribute 'guilds'
this file if that cog
you used commands.bot somewhere where you were supposed to use commands.Bot (capital B)
Everything is exactly a mistake
There is a way to save errors from the console into a file?
Type upload here as a file and or type of logs
if there are logs then I do not know how it is done
import discord
from discord.ext import commands
import datetime as DT
from discord.ext.commands import Bot
class Info(commands.Cog):
def __init__(self, bot):
self.bot = bot
#-----------стат----------#
@commands.command()
async def стат (self, ctx):
# main
servs = Bot.guilds
users = Bot.users
channels = Bot.channels
print(servs)
#-------------------------#
def setup(bot):
bot.add_cog(Info(bot))
print("Ког Инфо роботает")
In fact, I can use them and I have no problems
However, you should not.
Read the error it says max slash commands
They know..
he knew but he still posted the error
also
HOW DO I ADD A COOLDOWN
!d discord.ext.commands.cooldown
@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
in slash commands?
Depends on which library (or fork) you are using, if you are using edpy it's the same as normal commands decorator
Guys, how to indent in a embed?
If im using these invisible characters it will work for PC but on mobile it will output little boxes with "?" inside
Code is
embed.add_field(name=':blue_car: **__Fahrzeuge__** :blue_car:', value='@everyone die Abstimmung bezüglich der Fahrzeuge war eindeutig. Deshalb haben wir nun die Fahrzeuge angepasst und erhöht. Ab sofort findet ihr vollständige Autos und in größerer Menge. Gleichzeitig wurden die [#892752383107559444](/guild/267624335836053506/channel/892752383107559444/) angepasst. Also lest euch diese nun bitte erneut durch. Auf Altar wird es ab sofort auch keinen An- oder Verkauf mehr von Fahrzeugen geben.', inline=True)
How can I check if any occurrence in a list appears in another? (I am trying to see if a list of user ids are in another list of user ids)
def check_occurances(list1, list2):
temp = True
for i in list1:
if i not in list2:
temp = False
return temp```
Is this what you meant
I think I might have found I solution, but I'll test yours
(my solution)
list1 = [...]
list2 = [...]
if any(list1) in list2:
...
!d
any(list1) return a bool
Which in your case of user ids almost always returns True
Why would you want to check if True is in a list of another user ids
Idk if im being stupid not understanding your question though
I am just being stupid and forgetting how to use any xD
any return true if all values in the list are True(none empty string, numbers other than 0 etc)
ah
I found out how I'm supposed to do it :)```py
list1 = [...]
list2 = [...]
if any(id in list2 for id in list1):
...
I think you're supposed to use all() instead of any() if you want to make sure that all user ids are in the other list
But whatever works for you ig?
I might have made a mistake when i said any return true if all values in a list are it
Thats wrong
It returns true if any values in the list are true
Sorry about that
I don't want all, only one, but thanks for all your help
Can anyone help me in using motar for mongo db database
Not related to Discord bots
But looks like the Hocus Pocus theme
in file : ['hello', 'hi', 'bye']
with open(f'{path}/text.txt', encoding='utf-8') as f:
lst = f.read().splitlines()
print(lst)
lst.remove('hello')
print(lst)
result : ['hi', 'bye']
But it is not deleted inside the text file.
yes
because you never saved the file again with the new content
And it's not related to Discord bots, so you should check #❓|how-to-get-help
okay
and if its discord slash commands?
doesnt work.....
Idk about that
ok imma find docs
what did u do?
slash commands still work with cooldown iirc
i did @gilded grove_ext.cooldown
no shit sherlock you're supposed to do commands.cooldown()
is that a 3rd party lib?
how i can wait for multiple message at a time ?
i want to take all message in time
Is it possible to let my bot change its nick name in a server every 5 Minutes or 20?
use loop
k
task*
yes
just say(repeat after me)
Ole ole, I'm a guacamole
huh
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, loop=...)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
that's because it's no concrete item like a class or method, instead it's just a primer on the ext in general
welp tht doesnt work
Task exception was never retrieved
future: <Task finished name='Task-2' coro=<SlashCommand.sync_all_commands() done, defined at C:\Users\jason\chad\venv\lib\site-packages\discord_slash\client.py:415> exception=HTTPException('400 Bad Request (error code: 50035): Invalid Form Body\nIn options.1: Option name option is already used in these options')>
Traceback (most recent call last):
File "C:\Users\jason\chad\venv\lib\site-packages\discord_slash\client.py", line 491, in sync_all_commands
raise ex
File "C:\Users\jason\chad\venv\lib\site-packages\discord_slash\client.py", line 471, in sync_all_commands
existing_cmds = await self.req.put_slash_commands(
File "C:\Users\jason\chad\venv\lib\site-packages\discord\http.py", line 254, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In options.1: Option name option is already used in these options
Error?
Heyyy, can someoen help me with creating task? I need to start a looping task by command
How can i start a task using a command?
how to display the amount of deleted messages with this code?
@client.command(name='löschen', pass_context=True)
async def löschen(ctx, limit:int):
await ctx.channel.purge(limit=limit)
await ctx.send('Es wurden {limit} Nachrichten gelöscht! :white_check_mark: '.format(ctx.author), delete_after=5)
use limit ig
.purge() gives a list of the deleted messages back
So get the length of that list
Such as
x = await ....
len(x)
pugre
it's his language that he's using though
Thanks I know
So it is not possible to display it in this line
await ctx.send('Es wurden {limit} Nachrichten gelöscht! :white_check_mark: '.format(ctx.author), delete_after=5)
``` with the given information without adding more code?
But in German you often write oe instead of ö ;)
it is
thanks to you both
use an api
Yes you can, just put len(x) in your text and assign x to the purge() returned value
thank you mate 👍
using aiohttp*
?
aiohttp also does web requests 
Wasn't saying the requests library 
or requests
ok
!d discord.AuditLogAction but https://discordpy.readthedocs.io/en/stable/faq.html#is-there-an-event-for-audit-log-entries-being-created ??
class discord.AuditLogAction```
Represents the type of action being done for a [`AuditLogEntry`](https://discordpy.readthedocs.io/en/master/api.html#discord.AuditLogEntry "discord.AuditLogEntry"), which is retrievable via [`Guild.audit_logs()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.audit_logs "discord.Guild.audit_logs").
✨ indexing dictionaries like what any other normal python user would do ✨
try it and see
@client.command(name='löschen', pass_context=True)
async def löschen(ctx, limit:int):
await ctx.channel.purge(limit=limit)
await ctx.send('Es wurden',len(int), 'Nachrichten gelöscht! :white_check_mark: '.format(ctx.author), delete_after=5)
Forgive me if im not seeing the apparently, im a complete freshie 🙈
I did it with len, but it somehow gives me a TypeError: object of 'type' has no len()
Whats my mistake in here
the ö = oe I'll change later on 👀
!f-strings try assigning a variable to ctx.channel.purge
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
Soll ichs dir auf deutsch sagen? @twilit scarab
bru
Mir fehlen grade die Worte 😄 also dass das mit dem Int nicht funktioniert hab ich verstanden. Passt nicht vom "Typ" her, wie kann ich das funktionsfähig machen?
i guess you mean like x = ctx.channel.purge
and then len(x) ?
Int ist ein Typ fuer Variablen. Nummern. Du kannst keine Variable so nennen.
Du musst schreiben: "es wurden" + limit + "Nachrichten geloescht."
Falls limit die Zahl der geloeschten Nachrichten ist.
yes
or do what luna said
Okay ich werd das eben versuchen. Ja Limit ist die Zahl der gelöschten Nachrichten. Ich bin grad so happy das hier jemand unterwegs ist der Deutsch kann. 😄 Ist schwierig guten support ausserhalb der englischen community zu bekommen
I told him to just write: limit + "messages were deleted". Because limit is the number of deleted messages @boreal ravine
Ich programmiere jetzt auch seit so 4 Jahren 😂
❤️ thanks for your efforts too. It's just easier for me to understand
Woa, das war bestimmt auch ein struggle 😅 und an was arbeitest du aktuell?
That's true, I'm not here to replace anyone or kick anyone of their spot.
👍
Ich bin seit 2 Jahren jetzt Back-End Dev nachdem ich zwei Jahre Front-End war ;). Ich programmiere jetzt an WebProjects. Helfe Leuten, und will mir selber was dazuverdienen :). Ich helfe meist Leuten bei Projecten.
@client.command()
async def emoivb(ctx, channel: discord.TextChannel, *, new_name):
await channel.edit(name=new_name)
``` This should work. It edits the name of a Textchannel, but you can change that yourself too.
This is by channel-name.
Wow, und das alles ohne IT-Ausbildung? Ist auch ne gute Branche zum Arbeiten, nicht nur die Bezahlung auch in punkten "sicherer Arbeitsplatz". Ich hoffe doch, dass ich auch schnell dazu lerne und in ein paar Jahren was ordentliches hinbekomme:)
🗿
!rule 4
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
@thin valley@twilit scarab^
Ouh
get the channel object using bot.get_channel() or guild.get_channel() and then edit it
No problemo
how do i get a user avatar url in v2.0?
I dont use 2.0 rip
oh
!d discord.Member.avatar
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.avatar "discord.User.avatar")
just run a dir on that
k
your using a decorator
without a function
why
also this is gonna be invalid syntax and Ids are ints not strings
^
example of tasks.loop:
@tasks.loop(seconds=5) #loops every 5 seconds iic
async def your_function_name():
#code
your_function_name.start()
who told u that? and it isnt
this isnt
@client.command()
async def poll(ctx, *, text):
if not (ctx.message.author.guild_permissions.view_server_insights):
await ctx.reply("You do not have the permission to set up a poll")
return
options = text.split("|")
print(options)
embed = discord.Embed(title="Poll by a Member", description=f'''1. {options[0]}
2. {options[1]}''',color=ctx.message.author.color)
try:
with open("configure.json", "r") as f:
data = json.load(f)
channelToSend = data[str(ctx.guild.id)]["poll"]
channel = client.get_channel(channelToSend)
print(channel)
message = await channel.send(content=None, embed=embed)
await message.add_reaction("🅰")
await message.add_reaction("🅱️")
except Exception as e:
print(e)
await ctx.send("Please configure a poll channel first!")
why is this not working 🥲
IDs are integers, not strings
i said that before i dont know if he saw it though
https://discordpy.readthedocs.io/en/stable/migrating.html
Before v1.0, all snowflakes (the id attribute) were strings. This has been changed to int.
Quick example:
# before
ch = client.get_channel('84319995256905728')
if message.author.id == '80528701850124288':
...
# after
ch = client.get_channel(84319995256905728)
if message.author.id == 80528701850124288:
...
yo guys for whatever reason when i run my bot i get this error
does anyone know why?
guys, my code isnt working like this
if not (ctx.message.author.guild_permissions.view_server_insights):
await ctx.reply("You do not have the permission to set up a poll")
else:
options = text.split("|")
print(options)
well...copy paste the ID again
happens with me too
oof, try again
The channel is not in cache
ohh
Use get_channel and if it returns None, use fetch_channel
No
A simple one-line solution would be x = bot.get_channel(id) or await bot.fetch_channel(id)
mhm
thats what i was saying though
No
we dont need to write everything
channel.fetch_channel?
The way you said it was to replace it
yeah
what?
how do i get the creation date of a guild?
You shouldn't always make API calls, only if it's not in cache
!d discord.Guild.created_at
property created_at: datetime.datetime```
Returns the guild’s creation time in UTC.
^
what did you do
x = await bot.fetch_channel()
await x.edit()
``` its not that hard
x = await bot.fetch_channel(id goes here)
await x.edit(name="whatever")```

yes.
^
my bad.
why not not
get_channel is more reliable
how would we know if it isn't in the cache? there isn't like a thing to check if somethings in the bots cache isnt there?
I literally send
editing a channel isnt that hard cmon
my lord.
This uses fetch_channel only if get_channel returned None
how would you know if it wasnt cached or not
iirc this didnt have or before
You do you
🤷♂️
it always did
@quartz beacon this
Only thing I edited was
- channel => bot (typo)
- client => bot (typo)
- added
x =
kk
hey uh whats everyone's ig, greatest bot they've made?
A bot that answers questions for me
amazing.
If get_ returns None it means it isn't cached, then you would call it's fetch_ equivalent
..
A bot that searches a specific super car on a subreddit
Nah asyncpraw
Yeah lmao
How to make this multiple? for example
in the picture if someone say "Ping" bot will say "pong"
so i want add new different command with different answer from bot, how to that?
- Just add multiple if statements
- This isn't a command
- If you wanna make commands use the
ext.commandsextension
Thanks you its work!
bro
Why do you have a command inside an event
indentation wtf
Also you leaked your token
might wanna regenerate that
i always get this every time CTRL + C, but my code run well
Exception ignored in: <function _ProactorBasePipeTransport.del at 0x0000026D0E59C550>
Traceback (most recent call last):
File "C:\Users\Indra Constantine\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 116, in del
self.close()
File "C:\Users\Indra Constantine\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\Indra Constantine\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 745, in call_soon
self._check_closed()
File "C:\Users\Indra Constantine\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
is this okay?
i just learning python 3 days ago
Can I see the code?
A bot that automates things for me since I’m in a student organization and I have to manage meeting times per se but I just have the bot do it for me
That's normal, when you CTRL+C you don't properly stop the bot, doesn't matter anyways
Why use that and not bot command?and regenerate your token

@gloomy spindle Spamming is not needed, just as side note
You won't get more attention
Yeah that to
Ill give you less for being annoying
^
how would I remove this from the default help command
@gloomy spindle use #❓|how-to-get-help for your problems
bot.remove_command("help")
well that would remove it overall, idk if you can remove it from the default help command without making a custom one
hm
Why use the default help command and not a custom one?
if you make a custom help command, you can just use something like ```py
for cog, _cmds in mapping.items():
filtered_commands = await self.filter_commands(_cmds, sort=True)
if [c.name for c in filtered_commands][0] != "help":
# you could append all commands to a list or something, ignoring the help command```

platz = ""
for i in range(0, 100):
platz += "\n"
embed.add_field(name=':blue_car: **__Fahrzeuge__** :blue_car:', value=f'{platz} @everyone die Abstimmung bezüglich der Fahrzeuge war eindeutig. Deshalb haben wir nun die Fahrzeuge angepasst und erhöht. Ab sofort findet ihr vollständige Autos und in größerer Menge. Gleichzeitig wurden die [#892752383107559444](/guild/267624335836053506/channel/892752383107559444/) angepasst. Also lest euch diese nun bitte erneut durch. Auf Altar wird es ab sofort auch keinen An- oder Verkauf mehr von Fahrzeugen geben.', inline=True)
Hello i wanna indent my embed. So that it looks like the bottom. (l.a Image)
I just played around with the range but no effect shows up. Can you maybe help me out?
well \n wouldn't add whitespace, it would create a new line
and i'm not sure if theres a set way to go about adding whitespace
He can make a list of strings and for each one it will create a new line but idk if its efficient
he doesn't want new lines
new line
Would be great anyway. I just want that the start isn't connected to the 🚙 Fahrzeuge 🚙 . A new line would do it's job.
On the screen its done with 103x \u200b 🤡 😂
Subclass the help class.
https://gist.github.com/InterStella0/b78488fb28cadf279dfd3164b9f0cf96
If you want to change the name or something just pass in the no_category option.
I see
Well you can after the title make a new line and then you would be good
Because that’s objectively a trash option to what’s recommended.
embed.add_field(name=':blue_car: **__Fahrzeuge__** :blue_car:', value=f'\n @everyone die Abstimmung bezüglich der Fahrzeuge war eindeutig. Deshalb haben wir nun die Fahrzeuge angepasst und erhöht. Ab sofort findet ihr vollständige Autos und in größerer Menge. Gleichzeitig wurden die [#892752383107559444](/guild/267624335836053506/channel/892752383107559444/) angepasst. Also lest euch diese nun bitte erneut durch. Auf Altar wird es ab sofort auch keinen An- oder Verkauf mehr von Fahrzeugen geben.', inline=True)
Tried this too, didn't work :/
Just pressing space won't work. Adding invisible characters work for PC Output. On Mobile Phones you'll see white boxes filled with "?" so that's no option too
Idk what would happen but what if you put it at last of name
If anyone could lend a hand over at #help-avocado
I'll try
how to make it so that if a member has such a status, the bot will show an emoji of this status ???
Like if he has a status hes nickname will have a emoji?
Like online, offline, DND etc?
yes
!d discord.Member.status
property status: discord.enums.Status```
The member’s overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") instead.
Use this
whats enums ?
Do enums also contain the emoji?
It just returns one of the status enum
I knew their was one but didn't knew exactly lmao
Well, you need to add the emoji urself
class discord.Status```
Specifies a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") ‘s status.
It won't give you the emoji
Check what the status is and then use if statements to set the emojis
okey
DND will return dnd, Online will return online, Offline will return offline and Idle will return idle
thank you!
So
if discord.Status == "dnd":
#do something
or just check with discord.Status.dnd
Ye
Does the same, your choice what you choose and prefer to use
I personally love to work with enums
why not? making a custom one is much harder than using the default one
Can i give alias for client.command
yes
you can pass in a kwarg (aliases) in your bot decorator the values must be a list or a tuple though
I just make a command which is name is help and i send a list of the commands with a embed
Can you by any change lend a hand over at #help-avocado ?
the aliases kwarg
@bot.command(aliases=['cmd'])```
broooooooooooooooooooooo
are you getting help or giving help
i cant tel
any js dev here, i need a bit of help, its pretty easy question i think
python server.
!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.
js questions go here #ot0-psvm’s-eternal-disapproval
pefect name lol
how do I make a fight command? example:
user:!fight @x
bot: @y has started a fight with @x
bot: what to do? @y fight or block or kick
these are codes
@bot.event
async def on_message(message):
if message.content.startswith('!test'):
channel = message.channel
await channel.send('hm')
def check(m):
return m.content == 'hello' and m.channel == channel
msg = await bot.wait_for('message', check=check)
await channel.send(f'ok{msg.author.mention}')```
i am using on_message(message) so the user can reply with prefix
no !fight kick or !kick just kick till the fight is over
how do you edit contents of a embed?
Either resend the embed or use .to_dict
🤔
You copy, change stuff, and edit the message by reassigning the embed argument.
so u cant just use message.edit
You can.
Pseudo code:
e = discord.Embed() # whatever embed you make, k?
msg = await discord.Messageable.send(embed=e)
e.title = "new title"
await msg.edit(embed=e)
lemme test
and discord.Messageable will be either ctx, a channel, or any object which inherits send from discord.Messageable
i'll send the piece of code
Keep in mind that there is a total of five edits in a total of five seconds cooldown.
Hey @rain ridge!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
except:
convertTimeList = {'s':1, 'm':60, 'h':3600, 'd':86400, 'S':1, 'M':60, 'H':3600, 'D':86400}
time = int(timeInput[:-1]) * convertTimeList[timeInput[-1]]
if time > 86400:
await ctx.send("I can\'t do timers over a day long")
return
if time <= 0:
await ctx.send("Timers don\'t go into negatives :/")
return
if time >= 3600:
message = embed=discord.Embed(title="Timer")
embed.add_field(name="undefined", value=f"Timer: {time//3600} hours {time%3600//60} minutes {time%60} seconds", inline=False)
await ctx.send(embed=embed)
elif time >= 60:
message = message = embed=discord.Embed(title="Timer")
embed.add_field(name="undefined", value=f"Timer: {time%3600//60} minutes {time%60} seconds", inline=False)
await ctx.send(embed=embed)
elif time < 60:
message = message = message = embed=discord.Embed(title="Timer")
embed.add_field(name="undefined", value=f"Timer: {time%60} seconds", inline=False)
await ctx.send(embed=embed)
while True:
try:
await asyncio.sleep(5)
time -= 5
if time >= 3600:
await message.edit(value=f"Timer: {time//3600} hours {time %3600//60} minutes {time%60} seconds")
elif time >= 60:
await message.edit(value=f"Timer: {time//60} minutes {time%60} seconds")
elif time < 60:
await message.edit(value=f"Timer: {time} seconds")
if time <= 0:
await message.edit(value="Ended!")
await ctx.send(f"{ctx.author.mention} Your Timer Has ended!")
break
except:
break
except:
await ctx.send(f"Alright, first you gotta let me know how I\'m gonna time **{timeInput}**....")
there are some try: statements too
Use py after the 3 `
idk how it works
!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.
How can I get how many channels there are on the servers where there are total
Sorry what?
uhh
got it
!d discord.Guild.channels
property channels: List[GuildChannel]```
A list of channels that belongs to this guild.
Get the length of that, as it returns a list
Won't categories also be listed?
on the servers where the bot is located.
Find out how many channels there are in total
@rain ridge I want to write a simple command so you can learn from it:
@bot.command()
async def hello(ctx: commands.Context) -> None:
e = discord.Embed(title="Reply", description="Uh...")
msg = await ctx.send(embed=e)
e.add_field(name="\u200b", value="Hi?")
await asyncio.sleep(2)
await msg.edit(embed=e)
The guy who pays for winrar just told you
So I don't even know how to get this one out.
My question is how to get and not how to translate to

Sorry for English I'm Russian
any1 help?
There are three types of channels in a discord.Guild object. text_channels, voice_channels and stage_channels. If you need to find the number of all of those channels combined, you can use len(guild.channels), otherwise use len(guild.whatever_channels), or sum them with + as you need.
That's what I know
Hey, Im trying to create a way for the bot to send a msg at a specific clock time. I tried to do it with schedules but it didnt work. The bot just disconnects right after I start the script. is there any better way to do this or a way to fix it? I dont want to do it by using sleep I want somewhere to be able just type in a clock time for example 18:15 and the bot will send a msg everyday at that time.
!d discord.ext.tasks.loop
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, loop=...)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
here they told me there that the current does not work
sum([len(guild.text_channels for guild in bot.guilds]) + sum([len(guild.voice_channels for guild in bot.guilds])
len(guild.text_channels) + len(guild.voice_channels)
This is the output current of this server
You need from all of the servers combined?
and I need all the servers where there is a bot
len(guild.text_channels + guild.voice_channels)
bot.guilds
sum(len(guild.text_channels) + len(guild.voice_channels) for guild in bot.guilds)
Traceback (most recent call last):
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Baraban4ik\Desktop\Suzuki\cogs\info.py", line 97, in стат
channels = sum(len(guild.text_channels) + len(guild.voice_channels) for guild in bot.guilds)
AttributeError: module 'discord.ext.commands.bot' has no attribute 'guilds'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\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: AttributeError: module 'discord.ext.commands.bot' has no attribute 'guilds'
thx
What's the variable for your bot?
self.bot
How to get a channel
!d discord.ext.commands.Bot.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
it works like this sum(len(guild.text_channels) + len(guild.voice_channels) for guild in self.bot.guilds)
print(self.bot)
print(self.channel)
channelObj = self.bot.get_channel(self.channel)
print(channelObj)
<discord.ext.commands.bot.Bot object at 0x7f0fa3c0cdf0>
890646800019640380
None
None```
how to can i get the channel id from the channel itself where i command my commands?
ctx.channel.id?
aight
Try await self.bot.fetch_channel(self.channel). Wait... what's self.channel?
self.channel == 890646800019640380
He printed it.
I see.
channelObj = await self.bot.get_channel(self.channel)
TypeError: object NoneType can't be used in 'await' expression
I wrote fetch not get
How can I increase embed width in discord.py?
u dont use await in get_channel
only in fetch_channel since it's a coroutine
Not possible.
add invisible characters
You can add invisible characters to the title, description, field name, field value what caeden said ^^
And how to find out how many commands a bot has
len(bot.commands)
I literally installed python again and it shows me that...
what os
if linux, you need to install python-pip
Windows.
You can try py -3 -m pip install discord.py
Try repairing with the pyton setup
Outputs the current so len(ctx.bot.commands).
but it also outputs the event for some reason
for starters, does python or python3 do anyrhing. maybe you mean pip3 as well @shut axle
using discord components,
@bot.command()
async def leaderboard(ctx):
check = await lb_loaded()
if check == False:
await ctx.send("Leaderboard hasn't loaded yet, please try again in a few minutes")
return
starting = 0
to = 20
invis = ''
result = await get_positions(ctx.guild, starting, to)
async def lb_embed(pos):
embedVar = discord.Embed(title="Leaderboard:" + str(invis), color=ctx.author.color)
embedVar.add_field(name="** **", value=str(pos), inline=False)
embedVar.set_footer(text=f"guild: {ctx.guild}")
return embedVar
msg = await ctx.send(embed=await lb_embed(result), components=[Button(label='Previous', style=ButtonStyle.blue, custom_id='button_prev'), Button(label='Next', style=ButtonStyle.blue, custom_id='button_nex')])
message = ctx.message
interaction = await bot.wait_for("button_click", check = lambda inter: inter.message.id == message.id)
if interaction.custom_id == "button_nex":
starting = starting + 20
to = to + 20
result = await get_positions(ctx.guild, starting, to)
await msg.edit(embed=await lb_embed(result), components=[Button(label='Previous', style=ButtonStyle.blue, custom_id='button_prev'), Button(label='Next', style=ButtonStyle.blue, custom_id='button_nex')])
elif interaction.custom_id == "button_prev":
starting = starting - 20
to = to - 20
result = await get_positions(ctx.guild, starting, to)
await msg.edit(embed=await lb_embed(result), components=[Button(label='Previous', style=ButtonStyle.blue, custom_id='button_prev'), Button(label='Next', style=ButtonStyle.blue, custom_id='button_nex')])
getting the error "interaction failed"
anyone knows what's up?
this doesnt show events.
commands does not display events
return*
When I am trying to check the version of python it shows me that
even I already have python installed.
Have you tried repairing it atleast
I don't know, I have 7 commands output, although there are 6 of them.
And events 1
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "/home/runner/cogs/owner.py", line 1284, in on_raw_message_edit
if payload.author.id != self.bot.owner:
AttributeError: 'RawMessageUpdateEvent' object has no attribute 'author'
```help???
?
show code
@commands.Cog.listener()
async def on_raw_message_edit(self, payload):
if payload.author.id != self.bot.owner:
return
channel = self.bot.get_channel(payload.channel_id)
try:
message = await channel.fetch_message(payload.message_id)
except:
pass
else:
await self.bot.process_commands(message)
Have you checked environment variables in your computer
@shut axle did you make sure the box saying "Add Python 3.x to PATH" is checked?
Yeah i think he did
If not well thats the problem
Help
Which is the extraneous command being output?
@spiral frigate len(self.bot.commands) + len(self.bot.events)
That.
Okayt
Good.
As well as it does with Python 3.9.
the event is displayed
Oh great, I was reluctant to install it since I thought it might conflict
f it doesn't work @brazen raft
How are you viewing it? Through the default help command?
Manually add it to your environment variables.
If you have a custom implementation of the help command and it shows events alongside the commands, then your custom help command logic is most likely flawed
Well, like I have 6 teams and 1 event
Is it showing the event as a command on Discord?
And how to check it
The pip install discord.py shows this and not doing anything...
Guys, this is my footer and I want to add my discord profile next to my name, how to do that?
Like this
huh
!d discord.Embed.set_footer
set_footer(*, text=Embed.Empty, icon_url=Embed.Empty)```
Sets the footer for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Pass icon_url.
Why it is happening?
it is already installed
Embed.set_footer(*, text="Zeatman • 26.10.2021, icon_url="https://images-ext-1.discordapp.net/external/cJBUV5cIOm0u_YlsUia0EW4MpIM05dHrdb0maocfo3o/%3Fsize%3D1024/https/cdn.discordapp.com/avatars/371597683548225537/a_cc7d8579fb009c8f667ba781da9565c9.gif") await ctx.send(embed=embed)
Small e
Without *,
let me run
I have already done that
but
Now I have added this "
And the other link is not green
idk how to say that
I got it lol
!indention
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
What does this mean and what to do
did you close the string ? ( " at end)
Is indentation my error
I fixed the problem
cool
Either you read really fast or you just didn't read it.
line 3000 😳
I read but the error was shown in some line the the error pointer was on @
how to find out when the bot was launched
I suggest showing line 3117
Set the launch time.
!d datetime.datetime.now
classmethod datetime.now(tz=None)```
Return the current local date and time.
If optional argument *tz* is `None` or not specified, this is like [`today()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.today "datetime.datetime.today"), but, if possible, supplies more precision than can be gotten from going through a [`time.time()`](https://docs.python.org/3/library/time.html#time.time "time.time") timestamp (for example, this may be possible on platforms supplying the C `gettimeofday()` function).
If *tz* is not `None`, it must be an instance of a [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo "datetime.tzinfo") subclass, and the current date and time are converted to *tz*’s time zone.
This function is preferred over [`today()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.today "datetime.datetime.today") and [`utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow "datetime.datetime.utcnow").
Ignore this package
I still didn't understand you
How will I get the info there when the bot was launched
!d discord.on_ready
discord.on_ready()```
Called when the client is done preparing the data received from Discord. Usually after login is successful and the [`Client.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.guilds "discord.Client.guilds") and co. are filled up.
Warning
This function is not guaranteed to be the first event called. Likewise, this function is **not** guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.
add a datetime.datetime.now() variable before bot.run() and return it whenever you want the time of bot's launch
my team needs to find out when the bot was launched
I think he wants to just know when the bot is on. Not "when" as in time, but upon its launching.
Then use on_ready event.
Type so that the variable outputs: That the bot was launched on October 21...
sorry for my english I use a translator
I would just need a piece of code to output this
How do I make my bot stop adding channels? Cuz it’s just making a new channel until it reaches the limit and idk why
import discord
from discord.ext import commands
class test(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_message(self, message):
empty_array = []
guild = self.client.get_guild(900458404953333808)
channels = await guild.fetch_channels()
channel = discord.utils.get(channels, name=str(message.author.name))
if channel is None:
category = discord.utils.get(guild.categories, name="Tickets")
channel = await guild.create_text_channel((message.author.name), category=category)
if message.author == self.client.user:
return
if str(message.channel.type) == "private":
if message.attachments != empty_array:
files = message.attachments
await channel.send("[" + message.author.display_name + "]")
for file in files:
await channel.send(file.url)
else:
await channel.send("[" + message.author.display_name + "] " + message.content)
user = await message.guild.fetch_member(str(message.channel.name))
if message.attachments != empty_array:
files = message.attachments
await user.send("[" + message.author.display_name + "]")
for file in files:
await user.send(file.url)
else:
await user.send("[" + message.author.display_name + "]" + message.content)
def setup(client):
client.add_cog(test(client))
Use break to break the function
After creating your channel duh
Oh
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
After it makes the channel just use else:break or just add break at the bottom of the function
this doesnt seem to edit the embed what am i doing wrong?
if time > 86400:
await ctx.send("I can\'t do timers over a day long")
return
if time <= 0:
await ctx.send("Timers don\'t go into negatives :/")
return
if time >= 3600:
message = discord.Embed(title="Timer")
message.add_field(name="Bot",value=f"Timer: {time//3600} hours {time%3600//60} minutes {time%60} seconds", inline=False)
await ctx.send(embed=message)
elif time >= 60:
message=discord.Embed(title="Timer")
message.add_field(name="Bot",value=f"Timer: {time%3600//60} minutes {time%60} seconds", inline=False)
await ctx.send(embed=message)
elif time < 60:
message=discord.Embed(title="Timer")
message.add_field(name="Bot",value=f"Timer: {time%60} seconds", inline=False)
await ctx.send(embed=message)
while True:
try:
await asyncio.sleep(5)
time -= 5
if time >= 3600:
message.add_field(value=f"{time//3600} hours {time %3600//60} minutes {time%60} seconds")
await message.edit(embed=message)
elif time >= 60:
message.add_field(value=f"{time//60} minutes {time%60} seconds")
await message.edit(embed=message)
elif time < 60:
message.add_field(value=f"{time} seconds")
await message.edit(embed=message)
if time <= 0:
await message.edit(title="Ended!")
await ctx.send(f"{ctx.author.mention} Your Timer Has ended!")
break
except:
break
except:
await ctx.send(f"Alright, first you gotta let me know how I\'m gonna time **{timeInput}**...."
how to get them
^
exactly the time
Is this right

I made a command to ping you at the exact same time you tell the bot to ping you at, but how do I add a way so the bot will ping me at that exact same time everyday instead of just once?
This is what I got now
@bot.command()
async def p(ctx, chour=None, cminut=None):
if chour is None:
await ctx.send("You must give hour and minute in a 24 hour clock time")
elif cminut is None:
await ctx.send("You must give hour and minute in a 24 hour clock time")
else:
async def func():
channel = bot.get_channel(channel_id)
await channel.send(f"{ctx.message.author.mention}")
scheduler = AsyncIOScheduler()
scheduler.add_job(func, CronTrigger(hour=chour, minute=cminut, second="0"))
scheduler.start()
await ctx.send(f"Wew bot will remind {chour}:{cminut}")
why is it not editing the contents of embed?
Because you need to provide a new embed object when editing your message
Just like when sending
so it means i can add something else but can't remove existing one?
And edit only works on a message, not on an embed
mess = await ctx.send(...)
await mess.edit(...)
i'll see bout it
How can i disable commands per server wise ? I wanted to know what all info i should store on the db (aprt from guild id and stuff) and check the commands are disabled or not ? Would appriciate if any one could give me the ideology behind it
No
Use bot variables as shown here
import time, requests, nekos, sys, os, config
ModuleNotFoundError: No module named 'nekos'
Process finished with exit code 1
import time, requests, nekos, sys, os, config
so I have 2 files bot.py and info.py
info.py - cog
And there I use this variable.
where is the ratelimit list
use await ctx.send
How can I make the bot speak when a message is sent to the channel,
and then delete the past bot message and send a new one when the message is sent again?
The image is like fixing the bot's message at the bottom.
@spiral frigate For the 5th time
Use. Bot. Variables.
Error is explained
so
i got it
it tells me i need a arg so
I've decided everything
i just put None?
Well no?
'NoneType' object has no attribute 'send'
Since your function asks for a ctx parameter
im new to python i used to use golang
Give a ctx parameter
ok
ik
That won't do what they want
NoneType' object has no attribute 'send'
They want to disable the command per server, and not for every server
So adding dm_only will just block everything
They have to use a database to store guild ids and check if ctx is in it
its a long process
where can I find the ratelimit list?
Use a database, store the command name and guild id, and store a boolean
It’s still giving error that says “break” outside loop
Use return instead of break
can you tell when someone is spamming by using a bot? like
@client.listen()
async def on_spam(ctx):
if ctx.author.sendMessage < 0.1 seconds:
await ctx.send("stop spamming!")
or something like that?
Yeah
Is that pseudo code, or your attempt
thats pseudo
!d discord.ext.commands.cooldown
@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
how wont that help
so how would it work?
He doesnt want to cooldown a command
Ignore that
It won't help you at all
Hes trying to check if someone is spamming
ok
so like if someone started spamming hi hi hi hi hi hi it would say like stop spamming!
import discord
from discord.ext import commands
import datetime
import time
b = commands.Bot(command_prefix='not a bot')
b.remove_command("help")
time_window_milliseconds = 5000
max_msg_per_window = 5
author_msg_times = {}
# Struct:
# {
# "<author_id>": ["<msg_time", "<msg_time>", ...],
# "<author_id>": ["<msg_time"],
# }
@b.event
async def on_ready():
print('Bot is Ready')
@b.event
async def on_message(ctx):
global author_msg_counts
author_id = ctx.author.id
# Get current epoch time in milliseconds
curr_time = datetime.datetime.now().timestamp() * 1000
# Make empty list for author id, if it does not exist
if not author_msg_times.get(author_id, False):
author_msg_times[author_id] = []
# Append the time of this message to the users list of message times
author_msg_times[author_id].append(curr_time)
# Find the beginning of our time window.
expr_time = curr_time - time_window_milliseconds
# Find message times which occurred before the start of our window
expired_msgs = [
msg_time for msg_time in author_msg_times[author_id]
if msg_time < expr_time
]
# Remove all the expired messages times from our list
for msg_time in expired_msgs:
author_msg_times[author_id].remove(msg_time)
# ^ note: we probably need to use a mutex here. Multiple threads
# might be trying to update this at the same time. Not sure though.
if len(author_msg_times[author_id]) > max_msg_per_window:
await ctx.send("Stop Spamming")
b.run('stack overflow')
Never did that but I guess you'd need to save the message author and when the message got send, then compare the new message sent time with the old message sent time
Just stop
You're not helping anyone
Move on to another server
well I need help too
@bot.command()
@commands.has_role('- Hi Owners')
async def givelevel(self, ctx: commands.Context, member: discord.Member=None, *, lvl:int):
if member == None:
return
if ctx.guild == None:
return
result = await self.find_or_insert_user(member)
user_id, guild_id, xp, level = result
print(xp, level)
level = lvl
xp = 0
cursor = await self.db.cursor()
await cursor.execute('Update users set xp=?, level=? where user_id=? and guild_id=?', (xp, level, user_id, guild_id))
await self.db.commit()
await ctx.send(f"{member.mention} level changed to {lvl}")
``` i have givelevel command and its work fine but how to move it and make it work without cog
I guess you can simply copy paste like you did above to fix your issue
its nowhere on google
@velvet tinsel
So he needs a db?
I wouldn't use a db
is there a command like that like cooldown?
Simply a dict is enough
No, you need to code everything by yourself
K
i sent code
ok
Just stop already
Spoonfeeding is irrelevant
And you don't even understand the code by yourself
@leaden jasper
So don't do copy paste code from internet and think you're helping someone thanks
its just if statements and dicts
Then you can understand any game's code I guess
hm really
Simply some functions, loops, if statements and else statements
Now code a game please
I dont know what this means
You don't know yourself what the code does, so copy pasting is irrelevant
Just move on to another server if you want to send your copy pasted code
me? I know what it does
I think thats just gibberish
Your answer isnt really related to the question
well the code just uses if statements and dicts they can understand that on their own
they just wanted the logic
He wanted a anti spam
Let's just take popcorns and wait @slate swan
well i dont speak for them so ask them to see what they say to prove i'm wrong
Hes searching on stackoverflow give him some time
How do I log images? If my bot posts the image link to a logging channel and then deletes it then the link becomes invalid
Well that's how Discord works
Yeah
When you delete the message the content is invalid
Download the file and then send it
When you delete the image the image uploaded to Discord gets removed from their CDN
yeah I understand but is there any way for me to log it? Maybe like saving it locally then uploading?
If yes how?
How would I download?
So you can try to download the picture and hope it's not removed yet from their CDN
wait I need to check
My bot would first download then delete
@slate swan you're right, I shouldn't be spoonfed. I'll try to figure out on my own
I gave you a sort of logic for you
The api reference can be useful ig
Never really did it but should work fine
@slate swan what does cdn mean?is it like their logging server
For content
custom discord network idk
No, it's where attachments, files, etc. are sent and saved basically
saved yes
Content Delivery Network
Got it thanks
Most of the services have a CDN nowadays
Often https://cdn.website.com
Ok
I think u can use requests or aiohttp if u wana do it in async
There are good examples on the internet about how to download pictures with Python. Just make sure you use an asynchronous library
class discord.File(fp, filename=None, *, spoiler=False)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.
Note
File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
Tysm!
does self.bot.get_emoji(id) calls the API
I dont think so
dont work
!d discord.ext.commands.Bot.get_emoji
get_emoji(id, /)```
Returns an emoji with the given ID.
Yeah i think fetch()
yeah right ! , thanks
No problemo
Whats the difference of fetch and get does get searches for name or id of something and fetch will find it in discord?
fetch_ makes an API call to Discord, and get_ gets from the bot's cache
Yeah i thought so
Should use get_ and if it returns None, then use fetch_
Not recommend to always call the API
Yeah i know less api calls better
Yep
And it's just a few word more
Cuz of api abuse
x = get_ or fetch_
So yeah, worth it
It will get first right
Will try get, then fetch if it returned none
is there a way to DM a user?
!d discord.Member.send
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
oh yeah, I forgot 😅 thanks!
how can i send a message without a command
like using a function that has send in it
how do i run this def print_time(self, ctx: commands.Context, threadName): for z in split[int(threadName)]: if exitFlag: threadName.exit() try: ip = z server = MinecraftServer(ip, 25565) status = server.status() except: print("Invalid") else: print("Valid") channel = client.get_channel(902463513119842354) client.loop.create_task(channel.send("Found server: " + ip + " " + status.version.name + " " + str(status.players.online)))
how to get a user ID from this format <@&ID> py
Hey my snipe command takes these args
async def snipe(self, ctx, *, channel: discord.TextChannel = None):
My snipe command is working perfectly so as to for a user to use ??snipe and ??snipe #channel however they can also use ??snipe <user_id> to show deleted messages from that user for someone reason any idea why?
Why censor, as if we could do anything with your channel's id lmao 😂
When you invoked the command you didn't specify which member
You have to do command member not just command
its the author of the message
Then why add member as a required parameter
Remove it and instead of member use ctx.author.mention
I was about to say that lmao
thx it works 🙂
Yw
Must be faster next time ¯\_(ツ)_/¯
how can i send messages without a command so if i call another func
how do i call another func that sends a message
Im on mobile rn ok
Make the func take ctx or a message param and then send to the channel
So am I
Anyone have an Idea?
They can do that??
Yeah-
then does it need to be async
No idea why
Yeah it does
Weird 
ye then how do i call it using asyncio.run because it just gives me error
I have a problem with the anti spam detector + muting...
@client.event
async def on_message(ctx, message):
guild = ctx.guild
counter = 0
with open("spam_detect.txt", "r+") as file:
for lines in file:
if lines.strip("\n") == str(message.author.id):
counter += 1
file.writelines(f"{str(message.author.id)}\n")
if counter > 5:
# tells them to stop... and mutes them.
mutedRole = discord.utils.get(guild.roles, name="Muted")
# mutes them.
if not mutedRole:
mutedRole = await guild.create_role(name="Muted")
spam_msg = discord.Embed(title="Stop spamming!", description=f"because you were spamming, you were temporarily muted for 10 seconds from {guild}")
await message.author.send(spam_msg)
# waits 10 seconds until they are unmuted.
await asyncio.sleep(10)
mutedRole = discord.utils.get(ctx.guild.roles, name="Muted")
await message.author.id.remove_roles(mutedRole)
await message.author.id(f" you have unmutedd from: - {ctx.guild.name}")
then, if I keep spamming 'e', it returns with Traceback (most recent call last): File "C:[______________________________________]", line 343, in _run_event await coro(*args, **kwargs) TypeError: on_message() missing 1 required positional argument: 'message'
how do I fix that? I also want to mute them.
Oh you wanna run it using asyncio.run? How are you running it
on_message doesn't take any ctx param where did you see that
with that
Then?
so how do i run it
I was doing some testing. Thanks for the answer.
Should I send the code?
please include your code.
Ok.
On message doesnt need ctx as a parameter only message
or else we don't know what you're talking about
from discord.ext.commands import bot
from discord import game
from discord.ext import commands
import asyncio
import platform
import colorsys
import random
import time
bot = commands.Bot(command_prefix="=", case_insensitive=True)
# you don't need discord.Client()
# this is dming users with a certain role
@commands.has_permissions(administrator=True)
@bot.command()
async def announce(ctx, role: discord.Role, *, msg): # announces to the specified role
global members
members = [m for m in ctx.guild.members if role in m.roles]
for m in members:
try:
await m.send(msg)
await ctx.send(f":white_check_mark: Message sent to {m}")
except:
await ctx.send(f":x: No DM could be sent to {m}")
await ctx.send("Done!")
@announce.error
# feel free to add another decorator here if you wish for it to send the same messages
# for the same exceptions: e.g. @userinfo.error
async def _announcement_error(ctx, error):
if isinstance(error, commands.BadArgument):
await ctx.send(":x: Role couldn't be found!")
elif isinstance(error, commands.MissingPermissions):
await ctx.send(f":x: {ctx.author.mention}, you don't have sufficient permissions.")
else:
await ctx.send(error)
client.run("no") ```
not like that
Using asyncio.run or in another async func you await it
Im just clearing it
That isn't related at all with what they're trying to do
its Game
Yeah i know but he put ctx as a parameter in on message
big brain moment 🧠
Wrong person
TypeError: 'property' object is not callable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
await self.prepare(ctx)
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 789, in prepare
await self._parse_arguments(ctx)
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 697, in _parse_arguments
transformed = await self.transform(ctx, param)
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 552, in transform
return await self.do_conversion(ctx, converter, argument, param)
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 505, in do_conversion
return await self._actual_conversion(ctx, converter, argument, param)
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 476, in _actual_conversion
raise BadArgument('Converting to "{}" failed for parameter "{}".'.format(name, param.name)) from exc
discord.ext.commands.errors.BadArgument: Converting to "property" failed for parameter "member".
Who knows how to solve
code
@commands.command()
async def профиль (self, ctx, member: discord.Member):
print(member.id)







