#discord-bots
1 messages · Page 819 of 1
@edgy ospreyshow ur command for join n play first
ctx.voice_client i dont think that works
u need to save it as a variable or global or shit, and use it
@bot.command()
async def say(ctx, *, repeatshit="Nothing"):
await ctx.send(repeatshit)```
Ok tyy
I already regret sending that code
async def join(self,ctx):
if ctx.author.voice is None:
await ctx.send("Сперва зайди в голосовой канал")
voice_channel = ctx.author.voice.channel
if ctx.voice_client is None:
await voice_channel.connect()
else:
await ctx.voice_client.move_to(voice_channel)```
I cannot show the "play" command for technical reasons.
@edgy ospreyi use cogs and i do this, self.voice = await ctx.author.voice.channel.connect(reconnect=True, timeout=5500)
return in the first IF, PLEASE
ctx.author.voice.channel.connect <- has voice object
so i put that to a variableand use self.voice
= self.voice.play(FFmpegPCMAudio(url)
not every ctx gonna have ur voice-connectiion in it.
WHAT'S WRONG?
THERE IS EVERYTHING CORRECT
well, could be worse
https://github.com/discord/discord-api-docs/discussions/3216 @honest vessel
no, it's not
And what is wrong there?
go over every line, let's say ctx.author.voice is None, ok? go ahead, look
Well
well
as you can see, voice_channel = ... will already throw an error
you should return if the first IF is true
I'm having more problems...
with open(file, "rb") as f:
file = discord.File(f, "discordCommand.log")
embed = discord.Embed(
title="Log fetched",
color=c.teal()
)
await ctx.send(embed=embed, file=file)
Same error as last time, Cannot send empty message. Although, funnily enough, if I add this
ctx.send(open(file, 'r').read())
```before the 'open' statement, then they both work.
True,yes,true...
Hello , i want the calculator to turn off when the exit button is pressed . how can I write this code ?
have you read what I said?
do you know how to handle anything when a button is pressed yet?
I didn't understand what I need to do
set the state off all buttons to disabled?
just type return
under
await ctx.send("Сперва зайди в голосовой канал")
if u can code that calculator, u probally can figure how to give 1 button an action.?
im not coding this
Very helpful...
+2 errors
!d discord.ui.View.stop
stop()```
Stops listening to interaction events from this view.
This operation cannot be undone.
IN the IF
that return is wrong indentation
all you had to do here is add the return IN the IF
it has to be return await ctx.send()
that's a spoonfeed right there
oh yeah, I'm not helping at all, you're right 🤦♂️
in
@commands.Cog.listener()
async def on_message(self, message):
message_content = message.content
if "x" in message.content.lower() or "y" in message_content.lower() and message.author.id not in [botid, redactedid]:
await message.channel.send(content="z")
and
@commands.Cog.listener()
async def on_message(self, message):
message_content = message.content
if "x" or "y" in messsage.content.lower() and message author.id not in [ botid, redactedid ]:
await message.channel.send(content="z")
why is if "x" or "y" in messsage.content.lower() different than if "x" in message.content.lower() or "y" in message_content.lower() (as the latter doesn't work)
nvm i got answered
thats false, u can do
await...
return```
the first one is always true, be aware of what or does
it's identical if you're not using what the function returns anyways
you can, but return await ctx.send() works too
But you don't need to
But you said you need to. You don't
ok ok
i also try mean that put return alone is no crime
and prob easier for noobs to understand
yeah
Would anyone mind helping me with this?
but it's easier for the bot user if there is an await ctx.send() there
can u post both embed n file sametime?
isnt it like 1 or another
Not sure, but removing it didn't fix it.
with open(boost_filename_full) as fp:
prep_file = discord.File(fp, filename=boost_filename
try declare filename
Alrighty
file = discord.File(f, filename="discordCommand.log")
Nope, same thing
Indeed, especially because when I send the contents as text, the file sends
oh?
await ctx.send(embed=embed, file=file)
How do I make it do a log or send a message in a diffferent channel when a specific command is used
Like if i do !help here, it will send “!help used in #discord-bots” in another channel
try:
await ctx.send(embed=embed, file=File("discordCommand.log"))
Oki
Can someone help me?
You would have to get the ID of the channel, then use channel = bot.get_channel(id), await channel.send("something")
@mortal dovein ur code embed=embed, file=File(file))
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: expected str, bytes or os.PathLike object, not File
@commands.command()
async def clog(self, ctx):
if ctx.author.id not in [724811595976409119, 434405709321338895, 780239337933504552]:
return
file = "R:\\VSCode-Projects\\Discord-Bots\\Discord-Bots\\discordCommand.log"
# await ctx.send(open(file, "r").read())
with open(file, "rb") as f:
file = discord.File(f, filename="discordCommand.log")
embed = discord.Embed(
title="Log fetched",
color=c.teal()
)
await ctx.send(embed=embed, file=File(file))
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message
@commands.command()
async def clog(self, ctx):
if ctx.author.id not in [724811595976409119, 434405709321338895, 780239337933504552]:
return
file = "R:\\VSCode-Projects\\Discord-Bots\\Discord-Bots\\discordCommand.log"
# await ctx.send(open(file, "r").read())
with open(file, "rb") as f:
file = discord.File(f, filename="discordCommand.log")
embed = discord.Embed(
title="Log fetched",
color=c.teal()
)
await ctx.send(embed=embed, file=File("discordCommand.log"))
@honest vessel
you're overwriting the file variable, watch out
should be file_path for the first one
Same error
Hooray. The code is almost completely working. It remains to understand why the bot cannot send a message after sending the command.
async def pause(self,ctx):
await ctx.voice_client.pause()
await ctx.send("Пауза")
@commands.command()
async def resume(self,ctx):
await ctx.voice_client.resume()
await ctx.send("Возобновление")```
all that's left for you is to start READING errors
I couldn’t find it :/
last time it gave me this, File use used for getting file from path
Command raised an exception: TypeError: expected str, bytes or os.PathLike object, not File
did you copy this code?
yeah bro , i little know python
I don't understand what "can't be used in 'await' expression" means
ok to explain it better
ctx is (user of command)
each guy typing command has diffrent ctx
@commands.command()
async def resume(self,ctx):
await ctx.voice_client.resume()
await ctx.send("Возобновление") so how would this work?
its not the bots voice u resume?
there's more to your error
like "what line" / ...
Buttons and guis in general are hard to make, stick with what you know and build up your skill. Copying code does nothing for nobody, especially when it doesn't work.
it's worth saying that ctx means Context
yeah
and this @commands.command()
async def resume(self,ctx):
await ctx.voice_client.resume()
await ctx.send("Возобновление") for pause a bot from playing is wrong.
that is that guy typing command -> his voice
all right man, i just wanted to take the shortcut
there is none such thiing for a NoneType
error tells it
And what to do?
think about what you're doing
voice_client is None and you're trying to pause
first thing you need to do is add a check where you can only play and pause shit if the voice_client isn't None
@edgy ospreyif same ctx voice question its same still answer
if u say pause to command u dont tell bot to pause
or resume... await ctx.voice_client.resume()
u kinda tell urself
you are the ctx
u are the author
save bot's voice into a global varaible or use cogs what not
n say like self.bot_voice = <here u delecare voice object>
@honest vessel Ok I got it to work. No clue why it works now and not before but that's life. Code is below if curious ¯_(ツ)_/¯
when u connect bot set bot self.bot_voice or self.mybotvoice =
@commands.command()
async def clog(self, ctx):
if ctx.author.id not in [724811595976409119, 434405709321338895, 780239337933504552]:
return
file_path = "R:\\VSCode-Projects\\Discord-Bots\\Discord-Bots\\discordCommand.log"
embed = discord.Embed(
title="Log fetched",
color=c.teal()
)
await ctx.send(embed=embed)
with open(file_path, "rb") as f:
file = discord.File(f, filename="discordCommand.log")
await ctx.send(file=file)
that await on ctx.voice-balblabla.connect()
then u have bot voice object
what u doing now is just try make bot control ur voice
will nvr happen
cause its probally wrong but somehow those computers gets their own life
i am sure it wont work soon again
Me too, but I guess we'll get there when we get there. Thanks for help anyways :)
hey yall I made this work command and i don't get an error in the console py @commands.command(name='Work') @commands.cooldown(1,21600,commands.BucketType.user) async def Work(self,ctx): await self.open_account(ctx.author) users = await self.get_bank_data() user = ctx.author earnings = random.int(100,5000) em = discord.Embed(title = "McDonald's Worker", description=f"You worked as a McDonald's worker and you got {earnings} for your day of work!!") await channel.send(embed = em)
that's good
but only the cooldown gets sent once i use it once
u also nvr use users aka bank_data()
and i get no output
that not the prob the embed won't send
because i haven't made the bottem part yet
all u use is this
I was testing the top first
How do I add text to a white background that expands using pillow?
earnings = random.int(100,5000)
em = discord.Embed(title = "McDonald's Worker", description=f"You worked as a McDonald's worker and you got {earnings} for your day of work!!"
e = random.randint(100,5000)
send(e)
>>> {earnings}
all u do is declare a variable n post it
copy pasta economi bots 😛
Now the bot writes to the chat, but does not perform its main function.
Before editing the code, it was the other way around...
async def pause(self,ctx):
if ctx.voice_client is None:
await ctx.voice_client.pause()
await ctx.send("Пауза")
@commands.command()
async def resume(self,ctx):
if ctx.voice_client is None:
await ctx.voice_client.resume()
await ctx.send("Возобновление")```
are you using replit?
Yes
how did i guess?
iv told u 😛 u cant controll bot voice state like that
thats not bot's voice thats the one who runs command
Console appearance?
The chat icon
if ctx.voice_client is None:
await ctx.voice_client.pause()
this gonna try "pause" all who use this command.........
maybe ur a troll
No
I'm just a stupid Russian dude who uses google translator to communicate normally.
you're not in a vc
wow you missed a key part
I had random.int not random.randint
it would
on my error
why wouldn't it
ooh well am confused but i used random.randint cause thats how u do?
@echo waspi didnt see ur error 😉
I didn't have an error in console because of an error handler for the cooldown part
I commented it out and then noticed my error
@boreal ravinecause if i do @commands.command()
async whynot(ctx)::
ctx.voice_state.pause()
async def pause(self,ctx):
await ctx.voice_client.pause()
if ctx.voice_client is None:
await ctx.send("Пауза")
@commands.command()
async def resume(self,ctx):
await ctx.voice_client.resume()
if ctx.voice_client is None:
await ctx.send("Возобновление")```
Guess what? That's right, the code works at 50% again, now the bot performs its main function (stopping and playing music), but does not perform a secondary function (sending a message to the chat)
what
he's using the bots voice client
u sure?
!d discord.ext.commands.Context.voice_client <--
property voice_client: Optional[VoiceProtocol]```
A shortcut to [`Guild.voice_client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.voice_client "discord.Guild.voice_client"), if applicable.
Yes? read his code
voiceclient of the one aka author of ctx
no?
ok
When because of your stupidity you were recognized as a troll:
i just got this weird problem where when i on my bot nothing happens
Errors?
- Did you call the
runmethod? - Try running the file using command prompt/shell
can you tell me how to put the time in the bot's message as shown in this image?
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Scroll up a bit
How can I add this to embed?
Just like to normal text
!e from datetime import datetime
print(f'<t:{int(datetime.now().timestamp())}>')
@vale wing :white_check_mark: Your eval job has completed with return code 0.
<t:1644606031>
<t:1644606031>
Thank you!
Code
@bot.event
async def on_member_update(before, after):
channel = bot.get_channel(935160414965211179)
if after.bot:
return
if before.display_name != after.display_name:
emb=discord.Embed(title="Изменение ника", description="**__Информация:__**", color=discord.Color.from_rgb(255, 128, 0))
emb.add_field(name="**Пользователь ника:**", value=f"**{before.name}**", inline=False)
emb.add_field(name="**Ник до Изменений:**", value=f"`{before.display_name}`", inline=False)
emb.add_field(name="**Ник после Изменений:**", value=f"`{after.display_name}`", inline=False)
emb.add_field(name="**Сменил:**", value=f"**{before.name}**", inline=False)
return
await channel.send(embed=emb)```
why does not it work?
wrong?
yeah
Yeap
remove the second return
Ok thnks
Is it possible to find out who changed the user's nickname?
@quick gust
how to i make my deposit command so when someone runs &dep all it deposits all there money in the wallet to the bank?
rn i have &dep 100 they can't do all
Just get the money from the wallet, add it to the bank, cut it from the wallet
i already do that i just don't know how to do it with all
Thats what I said
Get the the value of the wallet
Add it to the bank, cut the max amount from the wallet
Ezzz
Every day at 5:00, I would like to display the time remaining until 5:00 the next day, how can I do that?
How i can send file with discord api? without discord.py
hi ash
that's what she said
?
Why?
because i need do it :)
Hiiii
;
Send raw requests?
isnt discord api discord.py?
oh nvm
No?
oh
Dpy is just a wrapper
:/
you have slowmode of 3 seconds smh 😠
Off-topic channels
There are three off-topic channels:
• #ot0-psvm’s-eternal-disapproval
• #ot1-perplexing-regexing
• #ot2-never-nester’s-nightmare
The channel names change every night at midnight UTC and are often fun meta references to jokes or conversations that happened on the server.
See our off-topic etiquette page for more guidance on how the channels should be used.
sorry
Beware Mina's birbo stabbo
no she'll !mute @velvet tinsel 20y
:/ not funny
I mean
eivl muted me for like 2 months
!ot and good luck
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
@commands.command()
async def citizenship(self, ctx):
#all citizenships citizenships
role1 = ctx.guild.get_role(938834958124978247)
role2 = ctx.guild.get_role(938834984515555458)
list_of_roles=[role1, role2]
citizenship=random.choice(list_of_roles)
#gce = grant citizenship embed
gce=discord.Embed(title="Congratulations", description=f"You have been granted {citizenship.mention} citizenship", color=0x4da917)
citizenshipdenied=discord.Embed(title="Sorry for the inconvenience!", description=f"This has been caused due to you already possessing {citizenship} citizenship.", color=0xff0000)
for citizenrole in ctx.author.roles:
if citizenrole in list_of_roles:
await ctx.send(embed=citizenshipdenied)
break
else:
await ctx.author.add_roles(citizenship)
await ctx.send(embed=gce)```
indeed, it works perfectly with 3 people, can't test with more but from what i've seen so far the so-called "rate limit" isn't that bad, all it does is slow down the process by a few seconds from time to time. but anyway, thanks for your time
The bot is supposed to cancel when someone has role in list and not give role
but the bot gives role and then says that it won't give role anyways
error:
in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: query is a required argument that is missing.
@client.command()
async def anime(self,ctx,*,query):
try:
anime = animec.Anime(query)
except:
await ctx.send(embed= discord.Embed(description = "No corresponding anime is found for the search query", color = discord.Color.red()))
return
embed = discord.Embed(title = anime.title_english, url = anime.url, description = f"{anime.description[:200]}...", color = discord.Color.random())
embed.add_field(name = "Episodes", value = str(anime.episodes))
embed.add_field(name = "Rating", value = str(anime.rating))
embed.add_field(name = "Broadcast", value = str(anime.broadcast))
embed.add_field(name = "Status", value = str(anime.status))
embed.add_field(name = "Type", value = str(anime.type))
embed.add_field(name = "NSFW status", value = str(anime.is_nsfw()))
embed.set_thumbnail(url = anime.poster)
await ctx.send(embed = embed)
pls help xD
When you run the command you need to enter in query
Also there should be spaces after your commas in the function parameters
And don't use a bare exception
It's very bad
ok 🙂
so i want 2 use cogs and stuff could anyone give me a template 2 get started with
i just copied my bot onto another computer and after installing all the dependecies, everything worked exept the voice, saying PyNaCl is not installed, however it is installed and I could see it on pip list(Its on ubuntu)
!d discord.Member.roles
property roles: List[Role]```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.
These roles are sorted by their position in the role hierarchy.
property permissions: discord.permissions.Permissions```
Returns the role’s permissions.
!d discord.Member.roles
property roles: List[Role]```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.
These roles are sorted by their position in the role hierarchy.
!d discord.Member.top_role
property top_role: Role```
Returns the member’s highest role.
This is useful for figuring where a member stands in the role hierarchy chain.
I just showed you
API never lies
Can someone help me?
I try to run this:
class Dropdown(nextcord.ui.Select):
def __init__(self):
selectOptions = [
nextcord.SelectOption(label="test", description="test2"),
nextcord.SelectOption(label="test3", description="test4"),
]
super().__init__(placeholder="test5", min_values=1, max_values=1, options=selectOptions)
async def callback(self, interaction: nextcord.Interaction):
if self.values[0] == "test3":
return await interaction.response.send_message("testtttt")
await interaction.response.send_message(f"you chose {self.values[0]}")
class DropdownView(nextcord.ui.View):
def __init__(self):
super().__init__()
self.add_item(dropdown())
@client.command()
async def test(ctx):
view = DropdownView
await ctx.send("test5555", view=view)
And get this as error:
Traceback (most recent call last):
File "C:\Python39\lib\site-packages\nextcord\ext\commands\bot.py", line 1055, in invoke
await ctx.command.invoke(ctx)
File "C:\Python39\lib\site-packages\nextcord\ext\commands\core.py", line 933, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Python39\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: TypeError: Object of type type is not JSON serializable
I'm not using json in this file / not imported
just reboot the bot
i am on vscode
Not wrong though
i run it and i stop running it but it doesnt go offline until like 20 mins
Just restart it?
Alternatively just use cogs
Full traceback?
Hey @ruby tinsel!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
hi so i have my discord bot and i set up a task using tasks but when its doing the task commands dont respond is there a way to make bot still be responsive ?
Can you show your code?
the task?
Tasks code*
Yes
@tasks.loop(seconds=60)
async def sendmsg():
with open("tracking.json", "r") as f:
data = json.load(f)
with open("UUIDS.txt", "r") as f:
uuids = f.read().splitlines()
# for id, players in data.items():
# for channel, uuid_list in players.items():
# for uuid in uuid_list:
# uuids.append(uuid)
async with aiohttp.ClientSession() as session:
limiter = AsyncRateLimiter(max_rate=120, interval=20)
async def fetch(uuid):
async with limiter:
async with session.get(f"https://api.hypixel.net/player?key={random.choice(API_KEYS)}&uuid={uuid}") as api:
api = await api.json()
result = await track(api, uuid)
return result
levels = await asyncio.gather(*(fetch(uuid) for uuid in uuids))
track() function is like 500 lines of code so im obv not gonna paste it here
So when my bot does a slashcommand it removes the message where the command was used when it replies to it, is there a way of just having reply without deleting the message?
Nope. It's how slash commands are made
So in other words gotta switch to prefixs?
Yeah
Gooot it, thank you!
Send all of it
Something is blocking aka not async
This is causing your bot to freeze
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
displayname = requests.get("https://api.ashcon.app/mojang/v2/user/"+uuid).json()["username"]
except Exception:
displayname = requests.get("https://api.mojang.com/user/profile/"+uuid).json()["name"]
stats = {"Star ⭐": bw_level, "Overall FKDR": bw_fkdr, "Solo FKDR": solo_fkdr, "Doubles FKDR": doubles_fkdr, "Threes FKDR": threes_fkdr,
"Fours FKDR": fours_fkdr, "4v4 FKDR": fives_fkdr, "Final Kills": bw_final_kills, "Solo Final Kills": solo_final_kills,
"Doubles Final Kills": doubles_final_kills, "Threes Final Kills": threes_final_kills, "Fours Final Kills": fours_final_kills,
"4v4 Final Kills": fives_final_kills, "Overall Final Deaths": bw_final_deaths, "Solo Final Deaths": solo_final_deaths,
"Doubles Final Deaths": doubles_final_deaths, "Threes Final Deaths": threes_final_deaths, "Fours Final Deaths": fours_final_deaths,
"4v4 Final Deaths": fives_final_deaths, "Overall Wins": bw_wins, "Solo Wins": solo_wins, "Doubles Wins": doubles_wins,
"Threes Wins": threes_wins, "Fours Wins": fours_wins, "4v4 Wins": fives_wins, "Overall Losses": bw_losses,
"Solo Losses": solo_losses, "Doubles Losses": doubles_losses, "Threes Losses": threes_losses,
"Fours Losses": fours_losses, "4v4 Losses": fives_losses, "WLR": bw_wlr, "Beds Broken": bw_beds_broken,
"Beds Lost": bw_beds_lost}
prefix = ""
didnt change requests
you installed aiohttp?
i tried to
do pip list in cmd
didnt work
probs doing it wrong
pip list doesnt work?
im using py ide
do it in console
ah ok
not python script
ok ty
why are you calling the timestamp
i wanted to add timestamp to embed
well you would use =, not call it
how do I use random.choice for an f string
em = discord.Embed(description = f"{workingList} **${earnings}**", color = discord.Color.blue())```
I want workingList to be a randomchoice
!d random.choice
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").
snake_case should be used for variable and function names
camelCase should be used for nothing
🗿
what
!pep8 everyone
PEP 8 is the official style guide for Python. It includes comprehensive guidelines for code formatting, variable naming, and making your code easy to read. Professional Python developers are usually required to follow the guidelines, and will often use code-linters like flake8 to verify that the code they're writing complies with the style guide.
More information:
• PEP 8 document
• Our PEP 8 song! :notes:
i keep on getting this error
even thou mememessage is a global variable
and when i try to use somewhere else
error
Show the whole code
U gotta define mememessage
@buttons.click
async def next(ctx):
global memectx
if ctx.member.id == memectx.author.id:
name,url,chosen = await searchredditformeme()
em = discord.Embed(title = name)
em.set_image(url = url)
em.set_footer(text=f"{chosen} | Your meme", icon_url=memectx.author.avatar_url)
global mememessage
await mememessage.edit(
embed=em,
channel = memectx.channel.id,
components = [
ActionRow([
Button(
label="Next meme",
style=ButtonType().Primary,
custom_id="next",
emoji = {
"id": "736655059382960313",
"name": ":catsmack:",
"animated": True
},
),
])
]
)
else:
await memectx.reply(f"That is not for you {ctx.member.name}")
I see MemeMessage in that code
Mmmm
Globals, yikers
the main aim of script
is that there is a meme
and there is button called next meme
when you click on it it will refresh and a new meme will appear
so i had a global variable to edit that message
Why though
because this variable is in a different subroutine
You're essentially making a paginator
Check this out
!e print('wee')
@pliant mortar :white_check_mark: Your eval job has completed with return code 0.
wee
!e hi = "2" print(hi)
@outer parcel :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | hi = "2" print(hi)
003 | ^^^^^
004 | SyntaxError: invalid syntax
ey
!e @client.command()
async def ping(ctx):
await ctx.send(f'pong {round(client.latency*1000)}ms')
@pliant mortar :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'client' is not defined
yeah that doesn't work like that
🗿
and #bot-commands
^
guys I got the D
🧐😳
the paginator is not what im trying to do because these new pages are random
it will generate random meme
oh ok
I adapted that same code to my wall paper command, which guess what? Generates new images
!e ```py
p = 0
print(p)
def l():
global p
p = 1
return p
print(l())
but i want to edit the message

oh wait
Then edit it?
i see now
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
@slate swan #bot-commands
ok ok ok ok
im very confused now
im using discord_buttons_plugin
so it will be @wintry jay.click
we want to check if user clicking it is user
then redo the meme command and edit the message
Btw
Why you're using an event
Use something else like disnake that has baked in button support and doesn't do it in a very weird way
While u can do wait_for?
because i have to do the same thing twice
im still confused why global does not work
Is that a library
Why are you using a 3rd party lib for button support
discord.py has baked in button support already
it was the only one i can find
Basically you have to define mememessage
^
ye but i did define it
Discord.py has button support
At least the 2.0 version
message_id = message.id
channel_id = message.channel.id
newchannel = client.get_channel(channel_id)
newmessage = await newchannel.fetch_message(message_id)
global mememessage
mememessage = newmessage
There is a 0% reason to not use discord.py for buttons
I use discord-components library

i use discord componenets for menu select
Just use disnake smh
can you even say discord-components is a lib
it is
It's so bad
it's just so noob
btw they shut their support server down
Could I get help doing stuff, I am kind of a noob at this.
ask without asking to ask
I more mean is this the right place to do that for Discord.py
Ye sure but im noob 
Alright, one second.
effort in profile picture
Okay, so here is what I would want help with is I have a bot that looks like this
class MyClient(discord.Client):
async def on_ready(self):
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
async def on_member_join(self, member):
guild = member.guild
if guild.system_channel is not None:
to_send = 'Welcome {0.mention} to {1.name}!'.format(member, guild)
await guild.system_channel.send(to_send)
intents = discord.Intents.default()
intents.members = True
client = MyClient(intents=intents)
client.run('token')```
and was wondering how I could add commands to start timeouts, ban people, or kick people to the bot?
And only let people with certain roles use those commands.
not sure why you're overcomplicating it so much
Well first you would need to use the bot framework
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
Alright.
I don't see a need to subclass anything yet
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
Check out this tutorial
If you have any questions or concerns, feel free to come back to this channel and ask/tell us
i have issues with my command
https://paste.pythondiscord.com/xacigegefu.py
so when people join the server it sents them a dm
indentation 
Guys is there a way to disable pings for a specific command?
also, just so we're specific, it's an event not a command @balmy ivy
!d discord.AllowedMentions
class discord.AllowedMentions(*, everyone=True, users=True, roles=True, replied_user=True)```
A class that represents what mentions are allowed in a message.
This class can be set during [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") initialisation to apply to every message sent. It can also be applied on a per message basis via [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for more fine-grained control.
do you want it to ping or not
yeah
nope
so when someone joins my server it sents them a dm
ty that will do
mmhmm
indentation?
i am new to this
in your send() method pass in allowed_mentions kwarg
@bot.event
async def on_member_join(member):
```now come on
it accepts anything with an AllowedMentions instance
deindent everything after @bot.event in that function
indentation
!indents
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
!indents
The bot itself does not ping
oop
wait sent me the code
what
The user does, i was wondering if it was possible to disable pings when actually calling the command
yeah that will prevent the bot from pinging users, you need to set users=False
@bot.event()?
no
I already have that but example
read the tag

User : >hello @compact ruin
That is not the bot its me and the ping will go through
Is there a way to actually stop this
yo
File "c:\Users\ja\OneDrive\Desktop\DISCORD BOT COGS\bot.py", line 5, in <module>
client = commands.bot(command_prefix = '.')
TypeError: 'module' object is not callable
PS C:\Users\jackr\OneDrive\Desktop\DISCORD BOT COGS>
look at the code again
`@bot.event
async def on_member_join(member):
embed=discord.Embed(title="Welcome", description="👋 Hello welcome to the League 🥳Have Fun Make sure to go follow the rules everything is listed in information ", color=0xe0e0e0)
await member.send(embed=embed)`
what do i change
huh
@compact ruin
yes thats it
and it's indented really wrong
thanks man
but theres no errors
Appreciate it
take a read here @compact ruin
do you have member intents?
yes
both in code and in the dev portal
show hos you enabled intents in code
@bot.event
async def on_member_join(member):
try:
channel = bot.get_channel(PUT UR CHANNLE ID)
memb = member.mention
em = discord.Embed(title=':heart: MEMBER JOINED :heart:', description=f"**Welcome to the server {memb}! Please take a look at CHANNLE NAME then go to [#861645234592546816](/guild/267624335836053506/channel/861645234592546816/)**", color=0x5528ec)
em.set_image(url='UR GIF')
await channel.send(embed=em)
print(f"{member} has joined the server.")
except Exception as e:
print(f'{e}')
huh
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
ffs
its not a welcome command it sents them a dm
bot = commands.Bot(command_prefix="...", intents=...)
👍
for VSolar
welcome
i have `bot = commands.Bot(command_prefix="$"
but you need to pass in your intents
read.
no spoonfeed
it's not even what he wants 
bot = commands.Bot(command_prefix="$", intents=...) like this?
oh
no
and to intents you pass something
yes read that
Okay, so I have the bot.py file, this is the main file, could I somehow split the different things it does like welcome messages, could I put the individual things into different python files, and then having the main .py files run the commands from these files.
I can give an example if wanted.
ok i did code intents now whats wrong with the code
!d discord.ext.commands.Cog
class discord.ext.commands.Cog(*args, **kwargs)```
The base class that all cogs must inherit from.
A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the [Cogs](https://discordpy.readthedocs.io/en/master/ext/commands/cogs.html#ext-commands-cogs) page.
When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta") are equally valid here.
use cogs
idk how
what did you pass in the intents kwarg
Yeah, found that, but I more mean could I get help actually doing that.
intents.members = True
bot = commands.Bot(command_prefix="$", intents=...)```
what
indentsize wtf
dude
thats what i copied
okay, so it's
intents = discord.Intents.default()
and you're fine
nvm i fixed it
well no
i had to import
intents=intents in commands.Bot
no
idk how to use cogs
from discord import Intents
intents = Intents.default()
intents.members = True
it's not cogs...
yes, now you pass intents to your Bot
where
bot = commands.Bot(....., intents=intents)
do not put the dots in your code
they're placeholders
commands.Bot( intents=intents)
this?
intents = Intents.default()
intents.members = True
commands.Bot( intents=intents)
bot = commands.Bot(command_prefix="$", intents=...)
this is what i have
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="$", intents=intents)
is it right?
thats not for you
@rustic stratus
tias
?
and, for everyone's well-being, please check out Python basics again incase you wanna do more experienced stuff
think so
Try it and see
it doesnt work
the bot should have access to the member
it didnt sent my alt
saved and restarted your bot
Member intents enabled?
left and joined the server
Bro?
well as far as I see
Saw that already, I read it but am kind of confused specifically on what to do.
ah
I wouldn't define intents that way. Just do intents = discord.Intents.all()
it works
And make sure intents are enabled in the developer portal too
yeah, as I said, it's not a command
no i knew it wasnt because i had to restart vscode
without presence intents
all()
...

Might just use a help channel, cause more stuff is happening here now.
Yeah, but I can't quite figure out exactly how to use it.
Okay.
guild = member.guild
if guild.system_channel is not None:
to_send = 'Welcome {0.mention} to {1.name}!'.format(member, guild)
await guild.system_channel.send(to_send)``` I want this in a different python file to clean up the main bot.py file, and then I want the bot to run this when the condition is met from the other file.
ok so in a cog (you subclass commands.Cog)
btw good prac to name classes with first letter upper case
Okay.
def setup(bot/client, depends on what you use)
bot.add_cog(name(bot))
client.add_cog(name(client))
And in ur main file
PascalCase
(Also, I advise putting the cog in a folder in the folder of ur main file
Yeah.
not needed
and bot.load_extension(foldername.filename)
Its not needed, but it's nicer
load_extension(name, *, package=None)```
Loads an extension.
An extension is a python module that contains commands, cogs, or listeners.
An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.
Well not entirely. If somebody does this it can lead to a sort of backwards camelCase. Try recommending PascalCase by name instead
👍
disnake event for timeouts?
So this in a different py file.
you gotta indent
Indent+ cog event
This isn't the main file.
Cog event == commands.Cog.listener()
Okay.
And I feel like I'm already spoonfeeding to much
that aint spoonfeeding
Sorry.
class MyCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def on_member_join(self, member):
pass
# this would ^
# VS
async def on_member_join(self, member):
pass
# ^ this would'nt fire
So this?
def __init__(self, bot):
self.bot = bot
async def on_member_join(self, member):
pass```
Sorry if I am asking to many questions., but I figure double checking doesn't hurt, right?
Forgot to define event
Oops.
@commands.Cog.listener()
async def ...
And in ur import: import discord and from discord.ext import commands
yes
oh yeah the listener deco
I can't see indents since I'm on phone
better way to do listener
@Cog.listener(‘on_ready’)
async def custom_name
yh, since u can only have 1 of each async def for example on_message
In cog listeners
from discord.py import commands
class greetingMessage(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_member_join(self, member):
pass```
This it now?
so u use @commands.Cog.listener("typeofevent")
async def whatevername...
Would work yes
U still need to add the cog tho
K.
At the end of file
U use bot, so
bot.add_cog(name(bot))```
Don't mind indents, phone pain
Just do 4 spaces 🗿
Smart
from discord.py import commands
class greetingMessage(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_member_join(self, member):
pass
def setup(bot):
bot.add_cog(greetingMessage(bot))```
This?
forgot :
def setup(bot):
Also
replace name with greetingMessage
def setup(bot):
bot.add_cog(greetingMessage(bot))```
From the main folder it's in 'cogs/greetingMessage.py'
Alright
make a list in ur main file in on_ready event
for extension in list_name:
bot.load_extension(extension)
print(f'Loaded{extension})```
I can't indent
Just make sure u got right indent, it's too hard on phone
So make a list with extensions, and point them to other .python files.
list_name = ["cogs.filename", "cogs.filename",...]
!d os.listdir
os.listdir(path='.')```
Return a list containing the names of the entries in the directory given by *path*. The list is in arbitrary order, and does not include the special entries `'.'` and `'..'` even if they are present in the directory. If a file is removed from or added to the directory during the call of this function, whether a name for that file be included is unspecified.
*path* may be a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object). If *path* is of type `bytes` (directly or indirectly through the [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike "os.PathLike") interface), the filenames returned will also be of type `bytes`; in all other circumstances, they will be of type `str`.
This function can also support [specifying a file descriptor](https://docs.python.org/3/library/os.html#path-fd); the file descriptor must refer to a directory.
Raises an [auditing event](https://docs.python.org/3/library/sys.html#auditing) `os.listdir` with argument `path`.
Just add this to somewhere around the start.
Yeah
Put it close to on_ready or somewhere easy to find
Whats the name of ur cog file?
list_name = ["cogs.greetingMessage"]
that’s a bad way
That's the way I use 🤷♂️
Alright, then I can use the commas to add more cogs.
True
you can use a for loop using listdir
It's a small bot, so it will would work for now.
and load each file
U can use it for now 🤷♂️
I can change it if I need to.
Just try it out
Send here for errors, imma go to sleep when u got it working
Can I get an update @rustic stratus ?
Yeah, the bot file won't stay open.
Error?
No error or anything, just opens than closes.
Hmmm
Are you running the cog?
If yes, don't do that. U only need to run the main file
It's the main file.
Ok
I can send the code if you want.
Sure
cogs = ["cogs.greetingMessage"]
for extension in cogs: bot.load_extension(extension)
print(f'Loaded {extension})
class MyClient(discord.Client):
async def on_ready(self):
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
@commands.command(name="ping")
async def ping(self, ctx: commands.Context):
"""Get the bot's current websocket and API latency."""
start_time = time.time()
message = await ctx.send("Testing Ping...")
end_time = time.time()
await message.edit(content=f"Pong! {round(self.bot.latency * 1000)}ms\nAPI: {round((end_time - start_time) * 1000)}ms")
intents = discord.Intents.default()
intents.members = True
client = MyClient(intents=intents)
client.run('token')```
This is the script without the token of course.
Removed the token of course.
I see that you use client
Where do you set your prefix
Looks like I forgot that.
hmmm
But would that make it crash.
Is it ok if @slim ibex helps you?
Sure.
Its 2 am and I really need some sleep
Yeah, that's okay.
Okay.
client.load_extension
And in the cog too
self.client = client
and def setup(client):
client.add_cog(greetingMessage(client))
He has a problem but I need some sleep rn
Bot keeps crashing when launching it.
bot hasn't been defined
also Client doesn't support cogs, you have to use the commands extension
Ahh.
commands.Bot might be what you're looking for.
He used discord.Client
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
Nvm
!d discord.Client
class discord.Client(*, loop=None, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.
A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").
Yeah that's what I was looking for
@rustic stratus are you facing any other issues?
@slim ibex he also used bot.load_extension etc when he uses client
Might wanna take a look at that, imma leave now. Have a good day/night everyone
well, try it out
Crashed.
Yes
inherit from commands.Bot..?
repl.it is just horrible, do not use it
^
Yeah there is
And that is what I like to call a screwup.
I used to use it
Why’s that?
Type hinting is good
thought ctx or context param just relates to context automatic
Im gonna look at videoz to learn how to code
oh well nvm
Well maybe
that’s what I heard
It will work without type hinting but linter wont be able to access the attributes of the Context class
Changed commands.bot to commands.command
So no intellisense for you
the machines are just severely underpowered, to the point where you would be waiting up to half a minute to get it ready to go. besides your computer is just a way better development environment than one of those instances.
shit time to add the type hint everywhere now
Yeah i agree, but what’s the best way to run my bot if i dont want my comp to always be on?
Server's could work.
I think it's really just if it runs python it can run this for the most part.
Correct me if I'm wrong.
repl.it isn't a hosting service.
how could i do this
do not treat it as such either, just go for a cloud computing service or host it on a machine somewhere
cogs = ["cogs.greetingMessage"]
class MyClient(discord.Client):
async def on_ready(self):
for extension in cogs: client.load_extension(extension)
print(f'Loaded {extension})
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
@commands.command(name="ping")
async def ping(self, ctx: commands.Context):
"""Get the bot's current websocket and API latency."""
start_time = time.time()
message = await ctx.send("Testing Ping...")
end_time = time.time()
await message.edit(content=f"Pong! {round(self.bot.latency * 1000)}ms\nAPI: {round((end_time - start_time) * 1000)}ms")
intents = discord.Intents.default()
intents.members = True
client = MyClient(intents=intents)
client.run('token')``` see issues.
What would you recommend? I’m using uptimerobot to send requests to the program rn so it doesnt fall asleep, so yeah, i def agree that i dont like replit lol
This still crashes.
Deploy on a VPS
You cannot create commands with discord.Client
You need to use the bot framework
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
let me ask you, what does "use commands.Bot " mean to you?
I don't really know, this is like, my second bot with discord.py
Google sounds like a good option. What’s the free service called?
Google Cloud.
you're just being ignorant at this point, if you don't know then you should ask more questions instead of ignoring others efforts.
I think.
im coding my discord bot on replit but its hard to add stuff without getting a eroor
replit is mega gay
and i dont know how to change stuff from message.channel.send to ctx.sed
don't use replit
replit sucks that’s prolly why
Use a vps
use either visual studio or pycharm
i have vscode
or sublime
Sorry, but I am trying my best.
but i cant use terminal
pass context to the function instead of message
if you're getting errors related to your code, that's not replit.
ctx*
im saying how do i change from messgae.channel.send to ctx.send
I know a free one thats 24/7 thats free without having to watch ads
pass ctx to function instead of message
from discord.ext import commands
class MyClient(commands.Bot):
....
inherit from commands.Bot instead of discord.Client
Okay, thanks.
ok
async def command(message) to async def command(ctx)
?
async def test(ctx):
await ctx.send("test")```
yes thats the eroor im getting on
from discord.ext import commands
cogs = ["cogs.greetingMessage"]
class MyClient(commands.Bot):
async def on_ready(self):
for extension in cogs: client.load_extension(extension)
print(f'Loaded {extension})
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
@commands.command(name="ping")
async def ping(self, ctx: commands.Context):
"""Get the bot's current websocket and API latency."""
start_time = time.time()
message = await ctx.send("Testing Ping...")
end_time = time.time()
await message.edit(content=f"Pong! {round(self.bot.latency * 1000)}ms\nAPI: {round((end_time - start_time) * 1000)}ms")
intents = discord.Intents.default()
intents.members = True
client = MyClient(intents=intents)
client.run('token')```
This?
try it and see 👀
commands.Bot has a constructor
Crashed.
import os
import discord
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as {0}!'.format(self.user))
it’s probably not working because there is no constructor?
also @commands.command() decorator won't work for a bot, it's meant for creating commands without binding it to anything. you should use @client.command()
Okay.
What would the decorator be?
Actually, let me see if I can figure out.
@bot.command I believe
difference between what?
It’s just based on what you name the variable
Ahh, okay.
bot and client
Still crashed.
!d discord.Client
class discord.Client(*, loop=None, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.
A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
I totally didn't forget to re add the token.
As I said, probably because you don’t have a constructor
unless yes you didn’t put the token correctly lmao
you should avoid replit
Nope, token is in, still crashed.
@rustic stratus
you should learn some Python OOP before doing a discord bot
bot = commands.Bot(command_prefix='?', description=description, intents=intents) Is this the constructor.
discord.Client just represents a discord client, with it you are able to receive events, send http requests to discord, etc. meanwhile, commands.Bot is a special subclass of discord.Client meant to provide the functionality that discord.Client does while supporting the commands framework. the commands framework makes creating bot commands super super easy peasy.
That is a way.
Okay, yeah, found this in an example.
what's wrong?
Okay, but I could use my method and it should work?
yes obviously, it's a class
Gonna add the logging and see if that shows why it still won't stop crashing.
How would you get input from multiple people?
that doesn't quite make sense, MyClient inherits Bot.__init__
for what
like a rock paper scissors command
return msg.author == ctx.author and msg.channel == ctx.channel
msg = await bot.wait_for("message", check=check, timeout=30)
def checktwo(msg):
return member != ctx.author and msg.channel == ctx.channel
msg = bot.wait_for("message", check=checktwo, timeout=30)``` would this work
should
ok
don't forget to handle the timeout error
ok
from discord.ext import commands
import logging
logging.basicConfig(level=logging.CRITICAL)
cogs = ["cogs.greetingMessage"]
bot = commands.Bot(command_prefix='?', description=description, intents=intents)
class MyClient(commands.Bot):
async def on_ready(self):
for extension in cogs: client.load_extension(extension)
print(f'Loaded {extension})
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
@Bot.command(name="ping")
async def ping(self, ctx: commands.Context):
"""Get the bot's current websocket and API latency."""
start_time = time.time()
message = await ctx.send("Testing Ping...")
end_time = time.time()
await message.edit(content=f"Pong! {round(self.bot.latency * 1000)}ms\nAPI: {round((end_time - start_time) * 1000)}ms")
intents = discord.Intents.default()
intents.members = True
client = MyClient(intents=intents)
client.run('token')```
See anything that would make it crash, even with the logging module, it doesn't make a log file.
does anyone know how to make this so like i do this command $pickup and it sents like one of these
wait why is logging introduced here
^
wdym
If it crashes and doesn’t show anything in the console, logging prolly won’t help
the client is the bot
this code is confusing me
they subclassed it because discord.Client will accept the on_ready method as an event handler
The console doesn't stay open.
logging module doesn't make a file like that sigh
stop worrying about logging, nobody advised that anyways
Oh, wait, docs say that.
Yeah, I figured that I could maybe get an error message though.
I need to go eat.
it's most likely that you misinterpreted it
Yeah, gotta eat, gonna be back in probably 30ish minutes if I could still get help then?
oh wait now i see it
you really only need this
class Bot(commands.Bot):
def __init__(self):
….
….
bot = Bot()
too many people using discord.py without learning basics of python
ik
unfortunate
Traceback (most recent call last):
File "C:\Users\nikit\PycharmProjects\test\venv\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\nikit\PycharmProjects\test\main.py", line 393, in checkt
await ctx.send(msg.content)
AttributeError: 'coroutine' object has no attribute 'content'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\nikit\PycharmProjects\test\venv\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\nikit\PycharmProjects\test\venv\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\nikit\PycharmProjects\test\venv\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: 'coroutine' object has no attribute 'content'
C:\Python310\lib\asyncio\events.py:80: RuntimeWarning: coroutine 'wait_for' was never awaited
self._context.run(self._callback, *self._args)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
@slate swan
thats what happens when run
wait_for() is a coroutine, it needs to be awaited
it is await though...
await wait_for(...) (it should be awaited)
msg = await bot.wait_for("message", check=check, timeout=30)
check more lines, python isn't lying to you.
oh shit im blind lmao
we've all been there lol
it works thanks
from discord.ext import commands
import logging
logger = logging.getLogger('discord')
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)
cogs = ["cogs.greetingMessage"]
bot = commands.Bot(command_prefix='?', description=description, intents=intents)
class Bot(commands.Bot):
def __init__(self):
for extension in cogs: client.load_extension(extension)
print(f'Loaded {extension})
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
@Bot.command(name="ping")
async def ping(self, ctx: commands.Context):
"""Get the bot's current websocket and API latency."""
start_time = time.time()
message = await ctx.send("Testing Ping...")
end_time = time.time()
await message.edit(content=f"Pong! {round(self.bot.latency * 1000)}ms\nAPI: {round((end_time - start_time) * 1000)}ms")
intents = discord.Intents.default()
intents.members = True
bot = Bot()
client = MyClient(intents=intents)
client.run('token')```
Is this correct?
pls learn python
Me?
yes of course
Move it out of the constructor?
seeing this makes me leave again from this channel
yeah you should learn OOP before jumping into dpy

The constructor is what is called when the object is instantiated
Everything else not part of the constructor should be a seperate method in the class
Okay.
methods like that could be like a method to establish database connection, load cogs, etc
trust me when i say this, put your discord bot project on halt. you are likely very frustrated or confused with your code not working the way you want it to, when in reality your knowledge of python is not developed enough to do what you want to do
Okay.
Learn OOP, how to organize the project, creating packages/modules, os module (might be used for things relating to discord bot)
in short: you don't know enough python, so don't pull your hair out, instead dedicate time towards learning fundamentals. heck, have some fun! make an interactive terminal chat bot, fiddle with classes and read a lot of documentation
Alright.
some of the best ways to learn include:
reading open source repos on github, reading documentation, reading examples, googling any and all questions you have, and getting practice with actually typing and getting a feel of the language
K
because it is a language, and should feel like a verbal one at that. you should try to improve on your ability to brainstorm ideas, and turn those ideas into functional code with fluency
especially with c# 🗿
Why are you subclassing?
Just start off with a simple setup for now
good luck, this is a really deep rabbit hole (although many people approach it and don't fall in)
Alright, thanks.
how do i make it so when i say a command the $hi deletes
await ctx.message.delete()
using the delete() function


