#discord-bots
1 messages · Page 988 of 1
ho okay
It has to be the event deco
!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.
oki oki
@client.event
async def on_message(message):
if message.author.id in blacklist:
return
await bot.process_commands(message)
looks cleaner still
Gg
Ik, but it's more lines
oh shit
yay it works now
0.01 byte space
guys how can i make the code that when my bot joins or leaves a server it tells me in a channel like this
I was invited to Server name.
await bot.process_commands(m) if m.author.id not in blacklist else None
@exotic kite
thanks hunter
not gonna work?
..
that doesnt help
Show code
Auto correct
i dont have one thats the problem
could have turned it off
@client.event
async def on_guild_join(g):
print(g)
Nah, I don't wanna sound like a 5 y/o
@bot.event
async def on_guild_join(guild):
channel = await bot.fetch_channel(id)
await channel.send(f"Joined {guild.name}")
hunter exposed
bro i dont want it to print it, i want it to send it to my channel.
Just use get_channel
tysm
@exotic kite
Dude it was an example
Thanks for spoonfeeding smh
;-;
there isnt a rule for spoonfeeding
dead chat
dont chat
dead chat, dont chat
tbh so true
See docs
@slate swan there's a reason we don't give away code (spoonfeed) but help them understand it.
If they want the code directly, they can always go to Stack
!d discord @slate swan
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
F
Ok sry

🧐
import os
from discord.ext import commands
from random import randrange
number = randrange(100)
number2 = randrange(100)
answer = number2 + number
client = commands.Bot(command_prefix="!")
@client.command()
async def math(ctx):
await ctx.channel.send(number number2)
if answer == True:
await ctx.send('True')
@client.event
async def on_ready():
print('Yo My Creator')
client.run(os.getenv('TOKEN'))```I'm trying to make the bot to send an expression and when user send the correct answer it says "True"
!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.
U can use ctx.send()
okay
@slate swan what do i do with this
@bot.event
async def on_guild_leave(guild):
channel = await bot.fetch_channel(id)
await channel.send(f"I left {guild.name}")```
Bruh
Then?
U can use if anser == number+number2
okay
@bot.event
async def on_guild_leave(guild):
channel = await bot.fetch_channel(id)
await channel.send(f"I left {guild.name}")```
it wont send that it left the server
Did u literally put id in the code
yes
I suggest learning python first
bro ik- im just not used with bot events
show ur code that u have put
this..
@bot.event
async def on_guild_leave(guild):
channel = await bot.fetch_channel(966361477055414374)
await channel.send(f"I left{guild.name}")
this
whats the error
Did u enable the intents
ty
uh
random question, can someone send me some articles/docs related to mapping data type? What I've read is related to the map() function and says that the func takes another func and some form of iterables as params however that isn't how the Type: of discord.AutoShardedClient.shards seems to say
https://discordpy.readthedocs.io/en/master/api.html#discord.AutoShardedClient.shards
Is this returning a list or a dict or something else (a mapping data type that I've never heard of perhaps)
What should I do to fix this?
File "/Users/hungdinh/mu_code/Learn Python.py", line 24
await ctx.send(number number2)
^
SyntaxError: invalid syntax
bru
send them in an f string
bro
Ur file name.
Do it
First
Ig he is starting from dpy
await ctx.send(f'{number}{number2}')
It’s generally discouraged
..
Sure but we want to avoid it as much as possible here
Sry
you don't learn much from getting spoonfeeded
And they come back later and bother us with similar questions because they didn’t learn anything the last time
..
it's true
Yes
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
We cannot help with music.
ytdl music*
What are you trying to loop?
And other illegal streamers
I think play function
Tbh I think almost everyone here tried it but regulars don't ask for help on it cuz they know it's against yt tos
Imagine discord making their own music service inside of discord
I dont think they will
Just like they made timeouts and threads - destroyed most of "simple moderation" and tickets bots correspondingly
Now only advanced ones remained useful
Weren’t they suppose to force all bots to go to slash commands this month?
Only verified ones
Message content intent will be restricted after aug 30 won't it?
Yea
Ohh ok. Verified >= 100 servers correct?
Yea iirc they postponed the date
75 to 100 yes
anyone know how to make a / command?
Yes I do!
@bot.slash_command(title="Hi", description="Hello")
async def hicmd(inter: Interaction):
await inter.send("Hello there.")
I think that is right
Depends with what library
library difference
I did this in nextcord
With dpy it is different (and bad imo)
Almost the same afaik
Just double checked it. They postponed it September 1st
And that means you can keep your bot on normal commands until that date
Ohh. Ok thx
Same thing
@spice folio Here, if you use nextcord this should work for you.
The owner needs 2FA
Enable 2 fac in ur account
He might need 2 Factor Authentification
ok i need it
Yea
SLASH COMMANDS WITH DISCORD.PY
from discord.ext import commands
from discord import app_commands
bot = commands.Bot(command_prefix="?", intents=discord.Intents.default())
@bot.tree.command(name="ping")
async def Ping(interaction: discord.Interaction) -> None:
await interaction.response.send_message("Pong!")
SLASH COMMANDS FOR DISNAKE (change disnake to nextcord for nextcord)
import disnake
from disnake.ext import commands
bot = commands.Bot(intents=disnake.Intents.default())
@bot.slash_command()
async def ping(inter: disnake.CommandInteraction):
await inter.response.send_message("Pong!")
The bot?
The account in which u login in developer portal
Cool
whats nextcord?
Yea he doesn't use it
i use replit
Oh god
lol
Oh god
Cool tutorial
Ikr
Nextcord is a discord.py fork
It’s a fork of discord.py
Spoonfeeding today 🙂
Yes
Ikr met 2 weirdos today who were just asking for code
Ash must have a blog website
not sure what this mean but cool!
People ask for my code and I send a rickroll to them 🤣
Lol
which is private and can only be accessed by certain users
I assume they probably got it from a tag though 
I send one of my projects so they can have "code"
I-
🙂
Just another module like discord.py that u don't need to worry about, if u use discord.py
ya i use discord.py
hunter knows everything
Yes
lmao
Then don't worry about it
I beg to differ
Should be Helper Yes
I agree
It's sadly not up to us 😔
I agree. He/she knows a lot about it. surprised they aren’t one yet.
Ok
He*
Thanks
..
lmao
Tho I saw the edit and the message, no need to delete it
20
I am not 20
it seemed odd
xD
22
Lower
Take this to an OT
Todays date is 20
Oh
2
Ye it is
Ur 16 ik
I got a ping from an OT channel
Lower
Same
how do i make my bots status on DND
Change it in the on_ready statement
He mean" how do i change"
No?
!d discord.Client.setup_hook
await setup_hook()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A coroutine to be called to setup the bot, by default this is blank.
To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.
This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.login "discord.Client.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready") event.
Warning
Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.wait_for "discord.Client.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.wait_until_ready "discord.Client.wait_until_ready")...
no
status=discord.Status.idle)
i dunno what to put here
for it to be DND
hey sparky
Yo
but will the db variable become a bot variable?
wrong sparky sorry
uh?
F
??
huh wtf?
!d discord.Status
class discord.Status```
Specifies a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") ‘s status.
nuu
hm, so if I use it in my cogs like
#all the cogs stuff
def __init__(self, bot):
self.bot = bot
self.bot.db
would it work though?
I do know about the attributes
It will work
hm tysm yerl and ryuga
I mean it would work but it's a weird place to do so.
hm so should I make an instance of the bot and create a bot variable?
Anyone know what’s wrong?
Haven’t touched python in over a year so I’m a little confused
I just have one file with a collection of useful stuff that always gets passed to my cogs.
conclusion?
Chat does not exists as a class member of chatbot
The best is to use subclassing, if you don't use that define the var in the place where you also define your client/bot
alright, I'm completely confused, thanks a lot
Lmao
..
..
Wow which lib for music
I meant a Client/ Bot object not a Cog
Yep scrolled a bit up, still why was he/she confused when I asked about the subclassing
Bot-instance.var
I got 3 vars in the init and other I set inside the setup hook
from datetime import datetime
import discord
from aiohttp import ClientSession
from discord import Client, Intents
from constants import config
from ext.backend.error_handler import CmdTree
from log import log
from ext.utils import Core, Fnine
class Dispy(Client):
https_session: ClientSession
def __init__(self) -> None:
self.owner_id = int(config.bot.owner_id)
super().__init__(
intents=Intents(),
application_id=config.bot.app_id,
owner_id=self.owner_id
)
self.launch_time = datetime.now()
self.tree = CmdTree(self)
async def setup_hook(self) -> None:
self.https_session = ClientSession()
self.tree.add_command(Core(), guild=discord.Object(id=config.debug.guild))
self.tree.add_command(Fnine(), guild=discord.Object(id=config.debug.guild))
await self.tree.sync(guild=discord.Object(id=config.debug.guild))
if config.debug.global_cmds:
await self.tree.sync()
async def close(self) -> None:
await self.https_session.close()
await super().close()
@staticmethod
async def on_ready() -> None:
log.info("Ready")
Yean nothing much, I'm only going to add a database object to this.
I used an async hack before with event loop but setup hook is a game changer.
And I need a custom solution to add my own cogs since Client doesn't have cogs :/
bot = ur bot
async with bot:
async with database...:
bot.var = ...
bot.start()
If ur db Conn can be used as a cm
Disnake has a setup func?
Not that hard tbh I'm just going to code it myself since i really don't want the bot to have a message prefix.
I can see why they didn't like that lol
I'm actually pretty close.
if module.ispkg:
imported = importlib.import_module(module.name)
for name, obj in inspect.getmembers(imported):
if inspect.isclass(obj) and issubclass(obj, Group):
Checking if subclassed item is Group, if it is Group it contains my slash commands.
I still need a way to call those classes and have it return it all recursively.
It's pretty gut
For this case then
Tbh I didn't knew it first I would like it more if they added it to inspect.
Way ahead of you lol
I checked it out but the only reason they have a setup func is to pass bot
And to have a more genuine check.
import importlib
import inspect
import pkgutil
from typing import Iterator, NoReturn
import ext
from discord.app_commands import Group
def unqualify(name: str) -> str:
"""Return an unqualified name given a qualified module/package `name`."""
return name.rsplit(".", maxsplit=1)[-1]
def walk_extensions() -> Iterator[str]:
"""Yield extension names from the exts subpackage."""
def on_error(err_name: str) -> NoReturn:
raise ImportError(name=err_name) # pragma: no cover
for module in pkgutil.walk_packages(ext.__path__, f"{ext.__name__}.", onerror=on_error):
if unqualify(module.name).startswith("_"):
# Ignore module/package names starting with an underscore.
continue
if module.ispkg:
imported = importlib.import_module(module.name)
for name, obj in inspect.getmembers(imported):
if inspect.isclass(obj) and issubclass(obj, Group):
# https://github.com/Rapptz/discord.py/blob/master/discord/ext/commands/bot.py#L899
# obj.__name__
yield obj
EXTENSIONS = frozenset(walk_extensions())
``` using this rn but it isn't finished, i got distracted making commands first lol
@slate swan Do you got a bot?
Can relate.
Back-end is just too fun.
Nothing you need relative imports.
how to make a bot that will ban any one who says something is unfunny on sight
Well, computers don't have a sense of humour so you'll have to tell them what's "unfunny" in order for them to detect unfunny/funny
then How Do i GIVE THEM a sense of umor
I would hope you don't
I would LIKE TO SHARE MY sense of tumor to the world
A computer with a sense of humour is terrifying
But to answer your questions, you would need to train a machine learning model
Gonna make an offensive joke
Have an API interact with said machine learning model, and using an on_message() event you can query the model for a positive/negative result and action based on that
mhm

What could be the benefit of using python instead of javascript for developing a bot?
All my time spending with DNN my time to shine.
Discord.py has more abstractions than discord.js does, if that's what you're asking
interpreter, easier to code, us, more support.
The message won't update and i get no errors:
@tasks.loop(seconds=60)
async def lb():
msg = await bot.get_channel(966068951626944522).fetch_message(966069258385756180)
db = mysql.connector.connect(
host="",
user="",
passwd="",
database="")
mycursor = db.cursor()
mycursor.execute(f"SELECT * FROM logs_info")
for i in mycursor:
text = f"User: <@{i[1]}> | Tickets: {i[2]}"
embed = discord.Embed(title=f"Middleman Logs", description=text, color=0x303135)
embed.set_footer(text="This message will be updated every 1 min.")
await msg.edit(embed=embed)```
do you start the loop?
its tasks.start() right?
yep
and it should be in my on_ready?
iy can be anywhere
*it
is it actually editing it?
itll show the time if you hover over the edited thing (test edit)
no
also, if you're using the same message for it every time, you should just fetch it once as a global to lower api calls...
not entirely sure why it wouldn't edit though, it can't be actually looping and going over the code? print something and see if it prints every minute
okay]
nothing prints
Yo
Can anyone suggest how do i make like 30min 1h and 1w
In giveaway
what i did was create a cog, create a command where a user can enter values for a time delta, add it to teh current utc time, and add data to a dict in the current cog. Then a background task keeps checking over and over until it finds a giveaway is over
but ig if you want asyncio.sleep works
but don't sleep for 10 days at a time lol
Ok..
why wont this welcome message work?
@bot.listen()
async def on_member_join(ctx, *, member: discord.Member):
await member.send("Welcome to the server!")
member.send?
dms the person
it needs positional args, like content='', image=discord.File etc
use @bot.event
it will eat commands
I don't understand
and also turning it into a kwarg is unneccesary
u mean typehinting?
send line 38 in coinflip
nope, just do py @bot.event async def on_member_join(ctx, member: discord.Member): await member.send("Welcome to the server!")
i don't think listeners work outside of cogs
u can do a example?
@bot.command()
async def hello(ctx):
embed = discord.Embed(title='Hey there')
await ctx.send(content='Hi!', embed=embed)```
ne message still
*no
do you want a message to the member or server?
dms
try the updated code i sent
i did
the line is ```py
await ctx.send(ctx.message.channel, "{}".format(random.choice(variable)))
i edited my previous message
what would you want to send a channel object?
Is there a good way to ensure I don't run into error 429 or too many requests?
await ctx.send(str(random.choice(variable)))
love u
legit nothing changed
depends, are you trying to nuke a server?
No, modmail
okay, show the event you have
@bot.event
async def on_member_join(ctx, member: discord.Member):
await member.send("Welcome to the server!")
!d disnake.on_member_join
Last night I left the bot idling. It pretty much just sends ban logs and handles mod mail, but it still ran into the error for some reason
disnake.on_member_join(member)``````py
disnake.on_member_remove(member)```
Called when a [`Member`](https://docs.disnake.dev/en/latest/api.html#disnake.Member "disnake.Member") leaves or joins a [`Guild`](https://docs.disnake.dev/en/latest/api.html#disnake.Guild "disnake.Guild").
This requires [`Intents.members`](https://docs.disnake.dev/en/latest/api.html#disnake.Intents.members "disnake.Intents.members") to be enabled.
hmmm
oh yes, don't pass in ctx
it's an event, not a command
forgot
@bot.event
async def on_member_join(member: discord.Member):
await member.send("Welcome to the server!")```
still no message
@opal cosmos have you enabled member intents for your bot?
So I'm not really sure what's causing that, but I figured I could add something that puts requests on "timeout" to all requests, I.e. checking the retry-after part and sleeping for that many seconds
https://i.imgur.com/xXNpz4Q.png
https://i.imgur.com/54FkCRM.png
Does anyone know if discord removed the nitro perms or something from bots? For some reason my bot only shows it on the server where the emojis are
why is this line producing this error?py Ignoring exception in on_voice_state_update Traceback (most recent call last): File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\client.py", line 375, in _run_event await coro(*args, **kwargs) File "C:\Users\Teagan\Documents\Coding\Zupie\bot\cogs\events.py", line 270, in on_voice_state_update f"Requested to speak: <t:{int(after.requested_to_speak_at)}:R>", TypeError: int() argument must be a string, a bytes-like object or a real number, not 'datetime.datetime'I tried wrapping it in a str() but it didn't like it
you need to convert that datetime object to an epoch
Python answers, examples, and documentation
is that as possible as adding .timestamp to it?
yes
oh cool, I'd removed that bc it had been giving me errors before (about a week ago is when I last touched it so I can't remember the error)
but hey it's working now
ok it says that i need to add a redirect uri on my developer portal when im creating an invite link but there are no options listed, what do i do
Code?
It's a pretty long one, but I already figured it out with some friends^^ Thank you anyways.
It's most likely a caching problems, as it just doesn't work in a specific channel
Send it in dms
@olive osprey
is the built-in help() command expected to work in private channels? I'm getting an exception Command raised an exception: AttributeError: 'Object' object has no attribute 'send' when I use it in a DM. Works as intended in the server.
hello i want the bot to read response
Why can't I import EmptyEmbed ?
ive made verify with random string and i wanna read response
send the tb
!d discord.client.wait_for
No documentation found for the requested symbol.
!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.10)"). 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.10)") 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.10)") 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**...
tb?
if you click into this, they have some good examples
traceback. The big error message
Ignoring exception in command kick:
Traceback (most recent call last):
File "/home/runner/Delta/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/Delta/mod.py", line 19, in kick
await self.bot.kick(member)
AttributeError: 'Bot' object h
Ignoring exception in command kick:
Traceback (most recent call last):
File "/home/runner/Delta/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/Delta/mod.py", line 19, in kick
await member.kick
TypeError: object method can't be used in 'await' expression
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/Delta/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/Delta/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/Delta/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: TypeError: object method can't be used in 'await' expression
yeah
thx it works now
also, my bot still wont send custom emojis
<:name_here:id_here>
thats right format right?
@bot.event
async def on_member_join(message):
await message.send(f"reply to this message with key: ||{key}||")
m = await bot.wait_for('message', timeout=60.0, check=check)
if m.content == key :
memberr = message.author
await bot.add_roles(memberr, roll)
await message.send('Role added')
else:
await message.send('Incorrect key')
``` i cant seem to get dm from bot
everything is defined
Do you want the bot to DM you?
Try:
await member.send("hi")
I also suggest implementing try and except statements to check if the bot is able to DM the user.^^
ty
Ah, wait, on_member_join takes member as argument, not message.
!d discord.on_member_join
discord.on_member_join(member)``````py
discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") join or leaves a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
i was thinking that too
Can we deploy a hangout(google chat) chatbot for free?
wym
wouldnt matter as the argument has been satisfied
Do we need google cloud paid service account for this?
Welp, Ig it looks better & if he works in the future with it, it will be easier for him to recognize his stuff^^
but yes argument naming is important.
^
I don't think this is the right channel for this
Okay
@bot.event
async def on_member_join(message):
await message.send(f"reply to this message with key: ||{key}||")
def check(reaction, user):
return user == message.author and str(reaction.emoji) == '👍'
m = await bot.wait_for('message', timeout=60.0, check=check)
if m.content == key :
memberr = message.author
await bot.add_roles(memberr, roll)
await message.send('Role added')
else:
await message.send('Incorrect key')``` bot wont read key
Where's key defined?
start of code
You are waiting for a "message", but your check() function is checking for a reaction. check will always evaluate to False and it will not parse your message
You aren't defining key
k
Ur using a reaction check for a message?
i have its random string
o yea mb
i was thinking of another bot
So I made a cog with slash commands using app_commands
@app_commands.command()
async def test(self, inter: discord.Interaction):
...
And I have a normal sync command
@commands.command()
@commands.is_owner()
async def sync(self, ctx: Context):
await self.bot.tree.sync(guild=discord.Object(id=305912183189929984))
await ctx.send("Slash commands synced")
But when it's synced the slash commands dont show up
@bot.event
async def on_member_join(message):
await message.send(f"reply to this message with key: ||{key}||")
m = await bot.wait_for('message', check=lambda message: message.author)
if m.content == key :
memberr = message.author
await bot.add_roles(memberr, roll)
await message.send('Role added')
else:
await message.send('Incorrect key');```
fixed this sorry for confusion @wise kettle and @torn sail
How can I make this thing in economy were if you buy something it will give me money every somthing seconds e.g I buy I manager then the manager gives me money every 3 minutes
hey, im trying to use slash commands now, but i keep getting a CTX error. Before my slash conversion, it worked fine though. Anyone know why?
Can someone assist me with warn, mute, ban, kick and timeout commands?
You do not use ctx in slash
you use inter instead
¯_(ツ)_/¯
@bot.command()
@commands.has_any_role(692760082085183519, 940008547993927691, 863878825376743475, 902292952381001779, 863879069253894166, 902292952381001779, 863879304110276668, 940008547993927691)
async def пред(ctx, member: discord.Member = None, *, reason = 'Отсутствует'):
print(45)
cursor.execute("""CREATE TABLE IF NOT EXISTS warning(guild_id BIGINT, user_id BIGINT, warn INT, count INT, moderator_id BIGINT, reasons VARCHAR)""")
base.commit()
print(1)
warnings = cursor.execute("SELECT * FROM warning WHERE user_id = ? AND guild_id = ?", (member.id,ctx.guild.id)).fetchone()
print("работает")
if member is None:
await ctx.send("Выберите участника")
return
if warnings is None:
cursor.execute('INSERT INTO warning(guild_id, user_id, warn, count, moderator_id, reasons) VALUES(?, ?, ?, ?, ?, ?)', (ctx.guild.id,member.id,0,1,ctx.author.id,'Отсутствует'))
base.commit()
print(2222)
cursor.execute(f'UPDATE warning SET warn = warn + 1 WHERE user_id = ? AND guild_id = ?', (member.id, ctx.guild.id))
base.commit()
await ctx.send(f"**{ctx.author.name}** Выдал предупреждение #{warnings[2]} {member} (случай # ) {reason}")
else:
cursor.execute(f'UPDATE warning SET warn = warn + 1 WHERE user_id = ? AND guild_id = ?', (member.id, ctx.guild.id))
base.commit()
await ctx.send(f"**{ctx.author.name}** Выдал предупреждение #{warnings[2]} {member} (случай # ) {reason}")
how to make it so that if the reason is not specified, then Отсутствует is not written in the chat?
how to pass several values through embed.set_image, namely, so that it randomly outputs one of 10 gif images
it's just that if you pass a variable where with the random module you get an error
!d random.choice use this
random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
@boreal ravine I did it through it, it gave an error
you didn't use it properly
@boreal ravine lmao how can it not be used properly ?
show me how you used it
random.choice(['lol', 'kek'])
that's not a url
only instead of lol and kek there were links
error?
Command raised an exception: TypeError: set_image() takes 1 positional argument but 2 were given
Do url=random.choice(...)
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
thanks
@boreal ravine what is the best way to use in order for the team to work a certain amount of time ?? Which module ??
@boreal ravine because when I was making buttons, people here told me that this module "import discord_components, Button, ButtonStyle from discord_components" was outdated
the team?
for example mute for a while
Source code: Lib/datetime.py
The datetime module supplies classes for manipulating dates and times.
While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation.
Not sure what I've got wrong with this:
@client.command()
async def test(ctx):
await client.send("Test complete!")
@client.event
async def on_message(message):
await modmail(message)
await autopublish(message)
await client.process_commands(message)
discord.ext.commands.errors.CommandNotFound: Command "test" is not found``` I've tried it both with and without ctx, and the reason why I'm using on message as I am is to allow for multiple on_message events
Is the command above your client.run?
Yes
it's ctx.send not client.send by the way..

on_message() is a built-in function. Its default behavior calls process_commands() to tell the client to process commands. As you are overwriting on_message(), you need to add an await client.process_commands() at the end of your function
he did that
wow im blind.
is there a better way I could be structuring this f-string?py embed.add_field( name="Afk channel", value=f"{f'{before.afk_channel.mention}' if before.afk_channel is not None else None} -> {f'{after.afk_channel.mention}' if after.afk_channel is not None else None}", )
Yeah it's just not finding the command for some reason
Use variables
before_channel = before.afk_channel.mention if before.afk_channel is not None else None
after_channel = after.afk_channel.mention if after.afk_channel.mention is not None else None
embed.add_field(
name=...,
value=f"{before_channel} -> {after_channel}"
)
!e ```py
afk_channel = None
print(getattr(afk_channel, "mention", None))
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
None
Instead of using a ternary condition you can just default a getattr
So you won't need that super long line
So, i made three buttons with discord-components - now i want to check if the button is clicked by the executing user.. currently its possible that everyone is able to press these buttons.
Any idea?
embed.add_field(name="Your turn!", value="Choose whats happening now", inline=False), components = [
[Button(label="less", style="4", emoji = None, custom_id="button1", disabled= False), Button(label="same", style="1", emoji = None, custom_id="button2", disabled= False),Button(label="higher", style="3", emoji = None, custom_id="button3", disabled= False)]
])
# [...]
interaction = await bot.wait_for("button_click", check = lambda i: i.custom_id == "button1" or "button2" or "button3") # less
if interaction.custom_id == ("button1"):
await interaction.send(content = "You choose less.", ephemeral=False)
# do stuff
since I have 4 of these long statements would it be better to do a getattr for each time or make a func for the egtaar and just call that func each time?
what's i?
so something likepy embed.add_field(value=f"{getattr(before.afk_channel, "mention", None)} -> {getattr)after.afk_channel, "mention", None)}not sure if I'd followed you correctly
Uh, i used https://devkiki7000.gitbook.io/discord-components/guide/getting-started - theres no explaination for that. Seems like its for the custom_id for the buttons.
I am currently pretty new at buttons and discord-components
do lambda i: i.custom_id in ('button1', 'button2', 'button3') and i.user == ctx.author to check if the user is the author
it should work
Gimme a sec, i try that.
Your second getattr call is weird, you flipped the paranthesis
Also your using double quotes inside of a string using double quotes
they need to be single quotes
oops parenthesis, yeah just noticed the quotes usage
anyone know a better place to host discord bots that isn't replit or heroku because they both suck
All free bot hosting sucks
Ask in #965291480992321536
alr
do filesize_limit and bitrate_limit update when a guild moves up a boost tier? and do those updates then call on_guild_update
with them backing up/ delaying. is this down to discord kinda limiting them or is it down to the code ?
do you have them installed?
it was working last night
when my friend helped me upload my stuff to github so he could help make my code cleaner
it like
stopped working
i forgot what i did with the folder, bc i was tired
did you have a virtual environment set up?
this is a good short guide https://discordpy.readthedocs.io/en/master/intro.html#virtual-environments
thx
do you know how to fix it tho?
do you have a folder called env (or something else perhaps) that has sub folders include, lib, scripts
this env folder should be inside the folder where the rest of your code is
yes
it is
but uh ive noticed
my friend had me move those files to the folder that gets uploaded to github
its not in my vsc folder anymore
that could be why huh?
yes and no,
yes that can be why it's not immediately picking up that the venv/env exists
but also no it won't stop you from accessing the venv/env
what does your file tree look like?
so just cd env right
I take it your on linux?
yes
okay so once your in the env directory you need to usebash bin/activate
How do you get a message object from a message ID with a predefined channel?
permission denied?
so from the top of the file tree it looks likeshell suede/env/bin/activate
maybe you need to be root user
I have very minimal Linux knowledge, the activate is a script tho
im the only user
weird
I like Windows
windows is only good because its ui and its easy for users, i would try linux because its less heavy and it doesnt spy on you but i game sometimes (rarely)
You should be doing . env/bin/active
Ignoring exception in on_guild_update
Traceback (most recent call last):
File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\client.py", line 375, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Teagan\Documents\Coding\Zupie\bot\cogs\events.py", line 129, in on_guild_update
icon_url=after.owner.guild_avatar.url,
AttributeError: 'NoneType' object has no attribute 'guild_avatar'```not really sure what's going on here, as far as I can see `after.owner.guild_avatar.url` is a thing, using `on_guild_update` event
I would recommend using some more modern venv tbh
Poetry is very very nice
@pliant gulch
quack folder is actually empty
bc my friend made me move my stuff from quack to suede
@flat solstice ^??
is there a env folder in the suede folder?
okay then go up to file at the top menu of vsc, select open folder and then select the suede folder
ohhhh
my env file didnt even upload
File "/home/rore/suede/main.py", line 233, in <module>
bot.run(TOKEN)
File "/home/rore/suede/env/lib/python3.9/site-packages/discord/client.py", line 723, in run
return future.result()
File "/home/rore/suede/env/lib/python3.9/site-packages/discord/client.py", line 702, in runner
await self.start(*args, **kwargs)
File "/home/rore/suede/env/lib/python3.9/site-packages/discord/client.py", line 665, in start
await self.login(*args, bot=bot)
File "/home/rore/suede/env/lib/python3.9/site-packages/discord/client.py", line 511, in login
await self.http.static_login(token.strip(), bot=bot)
AttributeError: 'NoneType' object has no attribute 'strip'
@flat solstice do i just make a new one?
yeah you don't want your env file uploading to github, it's 'unique' to your system config
it is ctx.guild.icon.url
or if using slash
inter.guild.icon.url
yeah ik, not what I'm after tho. I'm looking for the avatar of the guild owner (i.e. the avatar of a member
Hmmm
think I got it, it was a intents issue
or at least giving my bot all intents fixed the issue
https://paste.pythondiscord.com/ebuzejefok The code ive got works perfectly and posts all the chat logs the first time the code executes. but then when the loop comes after 30 seconds it doesn't post. I've been advised that its re-using the same cursor and it i need to make it create a new cursor? Could anyone help me, i dont fully understand how to do it. Been stuck with this problem for a good 4 weeks now, id really appreciate any help 🙂
how could I check if the Guild.system_channel is different between before and after whilst also allowing for either before channel or after channel to be none?py async def channel_check(self, before, after): return f"{getattr(before, 'mention', None)} -> {getattr(after, 'mention', None)}" if before.system_channel.id is not after.system_channel.id: embed.add_field( name="System channel", value=await channel_check( self, before.system_channel, after.system_channel ), )because I'm currently gettingpy Ignoring exception in on_guild_update Traceback (most recent call last): File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\client.py", line 375, in _run_event await coro(*args, **kwargs) File "C:\Users\Teagan\Documents\Coding\Zupie\bot\cogs\events.py", line 167, in on_guild_update if before.system_channel.id is not after.system_channel.id: AttributeError: 'NoneType' object has no attribute 'id'if there is no system channel in before. Using on_guild_update
hello can someone dm me to help me make my bot?
!rule 6
I'm not advertising I'm asking for help
Disable github integration
What's the best way to get the message object with ID from another channel?
Do you have that other channel's ID?
Yes
guild.get_channel(id).get_message(id)
?

It thinks you're using github, and it's tracking changes
And don't ask me how to turn it off lol
or something
Erm so i have a tiny problem, Im trying to keep prefix commands and use app commands however the prefix ones stop working when the / ones are active, what would be a way to keep the command names the same for both command types?
Is there any way to make a view without making a class that inherts discord.ui.View? I need to access local vars in some of the view's elements' decorators.
use commands.hybrid_command()
The exact same as commands.command() and provide most of the functionality of slash commands
Just be sure to define application_id in bot constructor
You should be able to pass in variables to a view when you create it, trying to use globals is a mess
If you're trying to dynamically add items, you can use View.add_item()
how do i make a autoresponder bot that responds with random messages to a key word like “no” or “yes”
hybrid_commands is not on the documentation so I'm unsure what you mean by this
Use on_message and check if it's a no or a yes and use the random module to psuedo-randomly pick responses in a list
When was this added may I ask?
Okay so I did that, but how do I change how it reacts to the selection? I feel like this has something to do with the method callback in the view but I do not know that much about Views
ok thanks 
2.0
python3.8 -m pip install -U git+https://github.com/Rapptz/discord.py (you need python 3.8 or later)
To install dev branch
aka hybrids
seems to be a recent change
https://caught-lackin-in-8k-by-cyberghost.cf/JIPYuYM6W2Lq
yeh
ik, i use sharex
and custom host
the variavle json was referenced before its assignment
how the fuc do i fix
!e
def a():
print(b)
b = 1
a()
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 4, in <module>
003 | File "<string>", line 2, in a
004 | UnboundLocalError: local variable 'b' referenced before assignment
basic py
so I have a hybrid command that works twice then the third time says this interaction failed, is this due to ratelimit or something?
Hey @normal lark!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
can someone tell me if there is an error? https://paste.pythondiscord.com/qivaraqupo
we arent your interpreter so try it out and see
Yes, I know, but when I try to !share (link), I can only use it after I have to restart the bot.
why
idk
Do you know anything about the share bot tiktok because I've been trying to solve my problem for 2 weeks but I can't?
https://paste.ofcode.org/J4yWczLqdvUQNFYrWtNWgw Does anybody know why self.context is ... at this point? The point of this is to make a view with the options being the bot's cogs, and then when a cog is selected it sends the cog's send_cog_help method. At line 36.
what library is that? discord.py ( if yes, be version specific )
and how do you invoke this command?
Oh sorry I didn't see your message. The lib is discord.py 2.0.0, and I just invoke it using >>help then choosing a random SelectOption from the menu. It breaks after that.
it comes from this line , you make a new instance of the HelpCommand and send the help with it, but it does not have an actual Context since it was not invoke by a message,
since you already passed the context into your SelectMenu, you can just ctx.send_help(cog) and it will work
Ah okay, I'll try it. Thank you!
mention returns a string.. <@&267628507062992896> and you're comparing it to @deleted-role which is also a string but it isn't the same
idk
if server.get_role(role_id):
# role exists
else:
# role does not exist```
heyo im trying to make a "boost count" command but im not rlly sure how the whole premium_tier thing works. someone able to explain it to me?
is it possible to get a list of a server's invite links?
I am trying to get the user name instead of the ID and remove the commas, and also list multiple people. What am I doing wrong?
o
How can I get the user name of the top 5 highest ranked people in the server
You forgot a "
How would I do that 😅, I do not use indexs or loops.
I use nextcord
xD
I know how to use databases and such, but not indexes or loops. 😅
Nah
I am making my own
I could always
I will learn loops and stuff
How can I fetch a role object?
From ID.
How can I make like the first command is ,setchan #1234
And then the bot uses the channel for the output of a particular channel
this is my code:
@bot.event
async def on_member_join(member, ctx):
Dis = breakpoint.get_guild(config.guildID)
embed = discord.Embed(colour=0x95efcc, description=f"Welcome to Nextvision! you are {Dis.member.count}", timestamp=datetime.datetime.utcfromtimestamp(1536229094))
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/933768511145250896/966459729738076180/n7dCH2pmCcaFVWXB.gif")
embed.set_author(name=f"{member.name}", icon_url="https://cdn.discordapp.com/attachments/933768511145250896/966459729738076180/n7dCH2pmCcaFVWXB.gif")
embed.set_footer(text=f"{member.guild}", icon_url="https://cdn.discordapp.com/attachments/933768511145250896/966459729738076180/n7dCH2pmCcaFVWXB.gif")
channel = bot.get_channel(id=962006966086025216)
await channel.send(embed=embed)
I need to do welcome discord bot but its not working and there is no error
Intents
You need intents
intents = discord.Intents.default()
intents.members = True
bot = discord.Client(intents=intents)
I have it
Try do discord.Bot
bot = commands.Bot(command_prefix = bot_prefix, intents = intents)```
oh ok
.
Just for example
setchan 1234
Bot: #1234 is now set for messages (only for that server)
And then when a user uses
message Hi
Bot should send the message Hi in the channel set for that particular server is this possible?
then do this
bot = commands.Bot(command_prefix = '.', intents = intents)```
@rain furnace is intents turned on in your bot settings too?
I dont think so
I would suggest we don't spoonfeed next time because we can see that they just blindly copy pasted it
How I turnning it on?
Huh?
Let's not spoonfeed them
There's nothing to be learned and I can see pretty clearly that they're just copy and pasting whatever you sent them without figuring out what does what or tweaking anything
Ok.
Thank you for your understanding
done
Does it work?
I am trying
ok
Fetch, get, or getch?
Get.
I think i've just found the answer though.
from discord.utils import get
role_id = 123
role = get(guild.roles, id=role_id)
like why?
Why what?
Why would you use utils.get()
Is there an error is it just not working?
guild.get_role() is O(1) (due to hash map implementation) while utils.get() is definetely not constant time
just not working
role_id = 2134532534
role = my_server.get_role(role_id)```
which is faster?
obviously get_role
get_role or discord.utils.get? i'm assuming get_role
hash map like i mentioned
I'm taking a stab at the dark and gonna say utils.get() is O(n^2)
yeah since utils.get loops through all roles
Since it loops not only the provided iterable but also each attribute of each item in the iterable
yeah
there is no error
I'm pretty sure it might also allow nested attribute searching which could take it way above O(n^3) or some other exponential time complexity
i told someone to use get_role over someone who said to use discord.utils.get because i assumed get_role is faster
Most, if not all, discord.py get_* methods are going to be the fastest
because most use a hash map
and we know hash map lookups are constant time
welp nice talking to you robin ima go back to fixing my wrapper's typehinting so mypy stops screaming
yup. good luck
.
!d discord.on_member_join on_member_join doesn't provide you with ctx
discord.on_member_join(member)``````py
discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") join or leaves a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
And what is breakpoint? The name of your bot instance?
no I am removing it I tried to do breakpoint because it didnt worked
Removing what? What didn't work?
the breakpoint and the code didn't work and there is no error
Okay, what is breakpoint?
That doesn't tell me much
I saw in youtube that many people using breakpoint for this line so I tried too
Okay. First things first stop following some terrible youtube tutorial. They're usually always bad and give you code that won't work
ok
Now, can you explain what you're trying to do so that I may assist you better?
Yes, I am trying to do welcome embed message
Oh, that shouldn't be very hard
Just construct the embed within your on_member_join, determine a channel to send it to, and send using await ctx.send(embed=embed)
ctx in a on_member_join event?
That's what I was thinking
discordutils music awesome 😩
There’s no ctx in on_member_join
The error is user has no attribute to name. How can I fix this?
Traceback please?
what is that?
why not
SELECT level, user from levels where guild = 123 ORDER BY level DESC LIMIT 10
nvm its his variable naming that confused me
Ignoring exception in command lblevel:
Traceback (most recent call last):
File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 168, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\Student\Desktop\Ayrus\main.py", line 231, in lblevel
embed.add_field(name=f"{user.name}", value=f"Level: {level[0]} | XP: {xp[0]}/100")
AttributeError: 'tuple' object has no attribute 'name'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 1048, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 933, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 177, in wrapped
raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'tuple' object has no attribute 'name'
Ah
lol its not a user object
await cursor.fetchone() returns a tuple
Ah
yeah
Default row factory...
doesnt all rows lol
Do I need that line at all then?
Set your connection to use aiosqlite.RowFactory
It provides things in a RowFactory object which has a lot more ways to access data
Same place as where you're initialising your connection
Will that affect my other tables?
It only affects the format in which data is returned to you
So it will
I'm not all that much of a fan of sqlite/aiosqlite or any of the connnectors so I don't know much about it, I usually use ORMs
It won't affect your tables in the way that it alters the data
That's... how it's always done
Ah
I am just trying to get some data to loop in a leveling rank command
it would be cool to have time comps in docs for disnake so i don't need to look up src code on mobile which is a pain
An extension for discord.py
Time comps?
You did ```py
@bot.command()
async def func(ctx):
pass
func[123]
Yes
Yes
Oh
Why can't I not do that?
Because functions aren't iterables
This is what I am doing
You can only superscript, e.g use [] on iterables or classes that implement the __getitem__ method
Or Generics, i think
hello i would like to know if something like this is possible py if message.author.id is not in users: code
sure
It's possible, though it doesn't do what you think it does
Actually that might throw a syntax error
well i want it to be oppsite than the in
fuction
if message.author.id not in users works just fine
is is for comparing if 2 objects are the same, e.g True is True
right
First line, role_name = role_name.split(":")
It doesn't know what role_name is so it can't split it
You can but you need to define the variable first
role_name = ... #something here
bot has no attribute emoji, and rightly so
Define role_name somehow
If ur trying to get the emoji the user sent, u have to access the content of the message
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
you can't add roles to a "user" but a "member"
And yes, there is a difference
guild_ = client.get_guild(GUILD_ID)
member = guild_.get_member(payload.user_id)
role = guild_.get_role(962639887876632666)
await member.add_roles(role) ```
Gives of a AttributeError: 'NoneType' object has no attribute 'add_roles' on the last line.
Looks like it couldn't mind a member with that ID
How?
time comprehensions
Yes.. what are those
the time a computer takes to finish a task/algorithm
Huh?
A time comp inside docs?
yes to show if its O(1) or O(n) cuz im tired of looking in src on mobile
😔
Ah..
member intents?
What?
!intents this.
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
I have intents already.
show the lines where you define them?
My error has nothing to do with intents, @sick birch said before a completely different issue.
Is it a command? Show the full code for it so we can see
its an event
its always because robin has the helper role😔
lmao
!d discord.Guild.get_member
get_member(user_id, /)```
Returns a member with the given ID.
Changed in version 2.0: `user_id` parameter is now positional-only.
No, it's under a on_raw_reaction_add function.
Hello
ill blame Danny for not mentioning tht it needs member intents to work
Full code is too long and the project isn't public.
My bot is not responding to any commands, but appears to be online once I run it
import disnake
import os
from disnake.ext import commands,tasks
from disnake.ext.commands import has_permissions, CheckFailure
intents = disnake.Intents.all()
client = commands.Bot(command_prefix="m/", intents=intents)
@client.event
async def on_ready():
print("Fun is online!")
@client.slash_command(name="test")
async def test(ctx):
await ctx.send(content="Hello World!")
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send('Please type in the full command.')
@client.command
async def check(ctx, member: disnake.Member = None):
em = disnake.Embed(colour=disnake.Colour.blue(),
title="**Middleman**")
em.set_thumbnail(url=member.avatar_url)
em.add_field(name="User Info:",
value="Id: User: ",
inline=False)
em.add_field(name="Vouches",
value="`150+`",
inline=False)
em.add_field(name="Servers:",
value="5",
inline=False)
em.add_field(name="Started Middlemanning:",
value="`15th of June 2021`",
inline=False)
em.add_field(name="Middleman Status:",
value="`Dm for middleman with a fee, no fee = block. Accepting non fee requests only in server requests.`",
inline=False)
em.add_field(name="Fee status:",
value="Middleman takes fees ands tips.",
inline=False)
em.set_footer(text=f"Requested by {ctx.author}")
await ctx.send(embed=em)```
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").
Example...
do you have an on_message event? if yes change the decorator from .event to .listen()
add () on the end of your commands
its client.command()
@client.command to @client.command ()
He does mention it though 
as for your slash commands, they take 1hr to register if they didnt appear yet
Ok! thank you!
@client.event()
TypeError: event() missing 1 required positional argument: 'coro'
Not really. They might be connected
event doesnt need those brackets
AttributeError: 'NoneType' object has no attribute 'add_roles'
guild_ = client.get_guild(GUILD_ID)
member = guild_.get_member(payload.user_id)
role = guild_.get_role(962639887876632666)
await member.add_roles(role) ```
i get an error on the last line.
👍
If you don't have the right intents the only members your bot can see is itself, so even if the ID is valid it may not "see" them
To whoever brought that implication up, thank you, I didn't think of that
Ah. I thought time comps as in like, list comps but with time. I was like, ???
But most of the time you can figure out the time complexity yourself. For example, utils.get is exponential time, get methods are all constant, etc
The bot can see everyone, I have many commands that use member intents and they work fine.
Then your ID is incorrect
yeah i just like making it shorter
member = guild.get_member(payload.userid)
payload.userid
there are only 2 reasons for get_member to return None
either you dont have member intents
or the id is wrong
yeah its pretty easy if you know your time comps well but its a pain to check github src on mobile
It may originate from some other guild
Well, that's an excellent time to learn your time complexities then!
You see those a lot in interviews, e.g what's the time complexity of a merge sort?
payload.user_id is a perfectly fine ID.
i was talking about explicitly mentioning that under the get_member method
Right, but it's a user_id which might imply that it may be originating from off-guild
robin are you ok? did you read my message or is that a statement not aimed at me
What?
I did, I'm just saying learning list comps is always helpful

not list comps
ah yes
🥺 💜
my brain is starting to malfunction
what if the member isnt cached

i wonder how that happens, does the wrapper just doesnt cache the member or does the gateway not send a MEMBER_CREATE event
ill have to check src again on mobile😔
even if its not cached on the gateway connect, it gets cached on other triggers if the required intents are on, and the memory is not being limited/ cache settings are not changed iirc
Usually the member will ALWAYS be cached. That is if the proper intents are given
yeah it should always be but sometimes it isnt
Without how the Gateway works, you get GUILD_CREATE for X guilds your bot can see, that is if you have the GUILDS intents
yeah
Since the gateway doesn't expose members inside of the GUILD_CREATE Inner payload
Your wrapper will send X GUILD_MEMBERS_CHUNK payloads to the gateway
This will then grab almost all of the members per guild, then they cache that
Which is what on_ready in discord.py waits for, using Futures
almost 🤨
Then from there on out, the cache is only updated by the GUILD_MEMBERS_ADD event, and the remove counter part
Still not working
My discord bot is not responding to my commands. Here is my code
Almost, because it depends on the payload you pass for the chunk
hey guys can someone point me in the right direction to learn how to edit an embed footer using a button?
add else: raise error at the end of your on_command_error event
import disnake
import os
from disnake.ext import commands,tasks
from disnake.ext.commands import has_permissions, CheckFailure
intents = disnake.Intents.all()
client = commands.Bot(command_prefix="m/", intents=intents)
@client.event
async def on_ready():
print("Fun is online!")
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send('Please type in the full command.')
@client.command()
async def check(ctx, member: disnake.Member = None):
em = disnake.Embed(colour=disnake.Colour.blue(),
title="**Middleman**")
em.set_thumbnail(url=member.avatar_url)
em.add_field(name="User Info:",
value="Id: User: ",
inline=False)
em.add_field(name="Vouches",
value="`150+`",
inline=False)
em.add_field(name="Servers:",
value="5",
inline=False)
em.add_field(name="Started Middlemanning:",
value="`15th of June 2021`",
inline=False)
em.add_field(name="Middleman Status:",
value="`Dm for middleman with a fee, no fee = block. Accepting non fee requests only in server requests.`",
inline=False)
em.add_field(name="Fee status:",
value="Middleman takes fees ands tips.",
inline=False)
em.set_footer(text=f"Requested by {ctx.author}")
await ctx.send(embed=em)```
My bot is not responding to any of my commands
With the default settings it will indeed request for all of the members in a guild
So, "almost" is just a worst case
The only time you'd have an uncached member is when your bot isn't fully ready
just edit the message with a updated clone embed
or if your memory is limited i suppose?
^ I'd appreciate it if someone could help me
.
@sonic lintel
Ok
and its member.avatar.url, not member.avatar_url
The garbage collector should be freeing and handling your heap memory so
your error handler is clearly avoiding your errors from raising
hmmm... im trying to use buttons to scroll through embed pages and i figured i could make it change pages by reading the page number from the footer but idk if its possible if i just send a clone embed
mhm cool
sure
check on paginators depending on your lib it should have examples
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/disnake/ext/commands/core.py", line 169, in wrapped
ret = await coro(*args, **kwargs)
File "/Users/alanabeaton/Database Bot/main1.py", line 24, in check
em.set_thumbnail(url=member.avatar.url)
AttributeError: 'NoneType' object has no attribute 'avatar'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/disnake/client.py", line 531, in _run_event
await coro(*args, **kwargs)
File "/Users/alanabeaton/Database Bot/main1.py", line 18, in on_command_error
else: raise error
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/disnake/ext/commands/bot_base.py", line 570, in invoke
await ctx.command.invoke(ctx)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/disnake/ext/commands/core.py", line 920, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/disnake/ext/commands/core.py", line 178, in wrapped
raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'avatar'
@slate swan
gotcha thanks for the help as always 👍
member is None
💜
How do I fix it?
you didnt mention anyone while using that command add py member = member or ctx.author in the first line of that command if you want it to be the user who used that command
Ok! thank you!
watch it be a ban command😭 💀
@slate swan Can you show me what it would be like in my code?
the source code says otherwise
it was a joke!
async def check(ctx, member: discord.Member = None):
member = member or ctx.author```
Thank you ^^
and the rest stuff you have below remains same
the or operator uses the second value if the 1st one is 0, None, [], "" or any Empty iterable
well then indent it according to your code...
you just need to add/remove few spaces :)
Thanks!
Help me
Sure
how to use "while"
while is a conditional loop, that means it will keep on performing the task until the condition is satified
i = 0
while i < 10: # the condition
print(i)
i += 1
I must program a coffee machine
in which I must include the "would you like another coffee?"
but it won't let me use "if" or "elif" after "while"
this is not really a question related to discord bots, have a look at #❓|how-to-get-help
I'm sorry
