#discord-bots
1 messages · Page 633 of 1
but where do i put in the code
\
at the bottom of the function
Where u wanna send an embed
Do I, then, just copy and paste it, into the code and/or message and/or string thingy?
thx
you copy the message returned on discord here into the string you are trying to send as the message.
@brittle ingot ?
Okay.
So, like this?
= !python
yes
but the command dosent wokr when i try to used i
@cedar stream
yes sure
what intents are required to allow a bot to send users a dm
So, like this:
if message.content.startswith("/see python emoji"):
| await message.channel.send("")```
?
.
try it. looks good to me
Awesome. Thanks! :).
what intents are required to allow a bot to send users a dm
the user needs to be in the same server as the bot.
thats it
whats is asyncio
can a bot operate without intents
or
yeah
!pypi asyncio
Don't use this package, this is for versions of python that don't have asyncio as a builtin
em so @brittle ingot i send an screenshot with error
which versions are those?
just import asyncio
Yes, effectively though… that is debatable
Why such a mistake?
Version's that can't use discord.py so not really relevant
Cus u put it in for loop, so it will try to get channel with that id for every guild, and only one guild has a channel w that id
em so...?
How else can this be done?
You can get the specific guild
it tells you the error…
bot.get_guild
Looks like bot has no attribute version
Then get channel from that guild
bot.version isnt a thing
What if I use multiple guilds?
so how could i make it
You can remedy this by creating a bot var named version with your bots current version.
if i dont have access to the account that owns the bot (say the account was disabled), but my bots verified, how can i get its name changed
or can i not..
oh
I don’t think you can. As that happened to a bot dev with a huge bot “Eli” and they had to discontinue the bot
In the bots main file right under the bot constructor put:
bot.version =“0.0.1”
Or whatever your version number is. Iirc
Verified bot's cant even change their username
!d discord.Client.edit
ig not
iirc, my friend who has a verified bot says discord doesn't allow them to change the bot's username after it gets verified
really?
Make sense, it’s like a branding thing
but how to i made in the code to not make more errors or something
colour=discord.Colour.()
How can I put there a colour code in?
Yea you can't change the name after verifying
Oof
!d discord.Colour || you would do color=discord.Color.red()
But Id
!d discord.Colour || you would do color=discord.Coulor.red()
class discord.Colour(value)```
Represents a Discord role colour. This class is similar to a (red, green, blue) [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)").
There is an alias for this called Color...
or you could just do color=0xffffff
fucking americans
thats a joke
lol, u aussie or something
pls no ban
How do I get the server IDs in the on_ready function?
Your doing the guild portion correctly. The issue is the channel ID. They are unique. Even if two servers have the same channel named “general” their IDs will be different. You need to change the portion where you are fetching the channel using the same ID every guild.
cuz i dont wanna make something worse
Errors will happen. It’s a normal part of programming. That’s why we are here 🙂
so what should i change in code
im getting the squiggly lines under all the ctx
because you said you were using an event, not ctx lol
i just used ctx for the sake of the example
you can replace it with an instance of discord.Message if you want
oh i have no clue what im doing tbh
what do you want to do?
!resources || may I guide you to the resources, where you can learn python at a more beginner level? discord.py is a bit intermediate
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Right under:
bot = commands.Bot in your bots main file try adding
bot.version = “0.0.1”
That will create a bot variable if I remember correctly. You should be able to access it throughout your code using: bot.version
#discord-bots message || i showed him exactly what to do, its a competence issue
just waiting for a message?
yes
you explained it pretty well
he did but i just don't know what im doing mb
oh alr
oki
so you understand it
i got invalid syntax
kind of
Just do guild_id = message.guild.id
.content is just the message that is received
line 13
I didn’t mean to copy the entire thing 🤣
oh
Yeah just remove line 13. Also double check your imports looks like you are importing OS twice
ok
Also note for anyone imports can be done on one line.
Import discord, os, datetime, random, typing
can a bot track messages of an embed
I think you copied what Moros wrote, and he's on mobile, so their "'s are different
what do you mean by this?
You mean embed content? Yes
once you have the embed object, you can look at the embed.description if thats what you mean
theres a bot that sends embeds of the chat of a game so track if in those embeds theres a specific word
!d discord.Embed.to_dict
to_dict()```
Converts this embed object into a dict.
and then do something
why do you have bot.version?
theres a bot that sends embeds of the chat of a game so track if in those embeds theres a specific word
@lament trail
yea, assuming the words are in the 'description', (they can also be in the fields though) you can access the content using embed.description
even if its another bot that i dont own?
yes
yes
nicee
its basically like reading messages but a couple extra steps
can someone help me with that?
!d discord.Message.embeds || you just need an instance of discord.Embed, which you can get from discord.Message.embeds
A list of embeds the message has.
ty mate ill try
oh
its a bot that sends chat logs of a game
is there a way to delete channels with a bot
Just gotta figure out which part of the embed has the content you want to check for. Usually description.
Yup
how would i do that
using the .delete() attribute on a discord.Channel object
!d discord.TextChannel.delete
await delete(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the channel.
You must have [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to use this.
!d discord.VoiceChannel.delete
await delete(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the channel.
You must have [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to use this.
idk why i did this, im too tired to remember discord.Channel
Lol
I’m so sad my computer broke
aw, what happened?
Iirc abc is usually for instances or conversion really
Shorted the charging port
damn :/
the command works
👏
The bot version is a bit weird… but awesome that it works!!
yeah
😭
so this any way to make is it better looking
What does the current code look like?
Remove the brackets. Essentially make sure the the bot.version variable only contains a string of 0.0.1 so should look like:
bot.version = “0.0.1”
Don’t copy cause I’m on mobile
@bot.command()
@discord.ext.commands.has_role("Server Booster")
async def snipe(ctx):
if (not discord.ext.commands.has_role("Server Booster")):
await ctx.send('Du hast ein Booster Feature entdeckt!')
return
channel = ctx.channel
try:
snipeEmbed = discord.Embed(title=f"Letzte gelöschte Nachricht in #{channel.name}",
description=snipe_message_content[channel.id])
snipeEmbed.set_footer(text=f"Gelöscht von {snipe_message_author[channel.id]}")
await ctx.send(embed=snipeEmbed)
except:
await ctx.send(f"Es gibt keine gelöschten Nachrichten in #{channel.name}")
so right now i need to add it in to my general bot not a testing bot
So, this is my code and I want that someones donesnt has the role that a message sends
who doesn't*
@discord.ext.commands.has_role("Server Booster")
async def snipe(ctx):
if (not discord.ext.commands.has_role("Server Booster")):
await ctx.send('Du hast ein Booster Feature entdeckt!')
return
channel = ctx.channel
try:
snipeEmbed = discord.Embed(title=f"Letzte gelöschte Nachricht in #{channel.name}",
description=snipe_message_content[channel.id])
snipeEmbed.set_footer(text=f"Gelöscht von {snipe_message_author[channel.id]}")
await ctx.send(embed=snipeEmbed)
except:
await ctx.send(f"Es gibt keine gelöschten Nachrichten in #{channel.name}")```
brackets in if statements 🤮
A little bit of JS flair in there 🤣
Ok?
The easiest way I could say would be to check within the command function instead of using a command check.
bot = slash_util.Bot(...)``` I'm trying to use the https://gist.github.com/XuaTheGrate/5690a3d9dadb280d3d15f28f940e02d1#installation library, what would I put in place for the 3 dots? I've never used cogs so this is all new haha
role = discord.Utils.get(ctx.guild.roles, name=“Server Booster”)
If not role in ctx.author.roles:
Send failed message
else:
Continue
don’t copy I’m on mobile
do buttons exist?
Externally yes, in discord.py itself not that I’m aware of. You could get a lib like discord-components, etc
okay
utils lowercase
but it's copiable

discord.py v2.0 has them
i have an question why i getting owner as none in serverinfo command?
do you have member intents
yes
i think i need to check
in the code no but in the developer bot portal i turnd them on
you need intents.members // intents.all to get owners
ok
The message does not want to be sent, what should I do?
oh i didnt know that i need
this
how do you get the user of who created the bot?
class PersistentViewBot(slash_util.Bot):
def __init__(self):
super().__init__(command_prefix=commands.when_mentioned_or('/', '.', 'c.'), owner_id=503641822141349888, intents=intents)
self.persistent_views_added = False
async def on_ready(self):
if not self.persistent_views_added:
self.add_view(PersistentView())
self.add_view(Ticket())
self.add_view(TicketClose())
self.add_view(AdminTicket())
self.add_view(Verification())
self.add_view(DropdownView())
self.add_view(ForceTicketClose())
self.add_view(HistoryView())
self.add_view(DropdownView())
self.persistent_views_added = True
activity = discord.Game(name="fc.coolmcgames.xyz", type=3)
await self.change_presence(status=discord.Status.online,
activity=activity)
print(f'Signed in as {self.user}')
bot = slash_util.Bot(command_prefix=commands.when_mentioned_or('/', '.', 'c.'), owner_id=503641822141349888, intents=intents)
class SlashCog(slash_util.ApplicationCog):
def __init__(self, bot):
super().__init__(bot)
self.bot = bot
@slash_util.slash_command()
async def hello(self, ctx):
await ctx.send('hi')
bot.add_cog(SlashCog(bot))``` How would I add the SlashCog bot to the PersistantViewBot? I'm trying to learn cogs and I'm stuck here on the documents haha.
@bot.event
async def on_guild_join(ctx,guild : discord.Guild):
#stuff
await ctx.send('thanks for the invite')
...
error:
TypeError: on_guild_join() missing 1 required positional argument: 'guild'
how can i introduce ctx as well as guild : discord.Guild to the event
without it seeing it as a required arg
!d discord.on_guild_join || it only takes guild, not ctx.
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.
so how would i get the bot to send a message to the top channel once it joins?
intents.all()
ok
you figure out what the top channel is -> there no ctx because it wasnt invoked
is there any way i can define ctx within the class?
import discord
from discord.ext import commands
from discord.ext import commands, tasks
import asyncio
from itertools import cycle
import os
import json
import random
import datetime
import requests
import aiosqlite
from typing import Text
import aiohttp
import platform
from discord.ext.commands import clean_content
intents = discord.Intents.default()
intents.members = True
intents.all() like this?
intents = discord.Intents.all()
no…because its not being invoked in a channel…
but still it showing owner as a none
then you didnt do the intents correclty
!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.
but i need to get owner as like @slate swan not as a none
400 Bad Request (error code: 50007): Cannot send messages to this user do we need intents to dm users?
nah it just means they dont have open dms/you dont share a server with em
its meant to continue though if the user cant be dmed
intents = discord.Intents.all()
you caught the wrong exception then
.
ive tested this on a bot without verification and with all intents enabled (it worked perfectly fine) but now im testing it on a bot thats verified with to my knowledge no intents enabled, and it just wont continue if the suer cant be dmed
still
@bot.event
async def on_guild_join(guild : discord.Guild):
members = guild.members
for member in members:
try:
#embed stuff
await member.send(embed=embed)
print(f'dmed {member.name}#{member.discriminator}')
except Exception as e:
print(e)``` i was given authorization by the server owner to do this, servers very small
so whats the problem?
its in a loop, not sure why it doesnt continue if it finds a user that cant be dmed
ugh
are you sure its not continuing?
can i add ctx when subclassing help command? like async def send_bot_help(self, ctx, mapping):?
yep, otherwise id get dmed
no, you didnt. read what i wrote and look what you wrote
you need to remove the intents = Intents.default() above
change intents = discord.Intents.default() to intents = discord.Intents.sll()
and the intents.members
@slate swan are you able to help me at the moment
so what should i do
apparently not he's muted
lol
Bro im having so much trouble making the dumbest cog ever
i havent tested yet but i know it wont work
you need to unindent def setup outside if the class
and the @commands.group needs to be indented inside
Traceback (most recent call last):
File "C:\Users\PC\Desktop\Dadudeł Bot\Dadudeł Bot.py", line 17, in <module>
intenes.members = True
NameError: name 'intenes' is not defined wth
intens
class PersistentViewBot(slash_util.Bot):
def __init__(self):
super().__init__(command_prefix=commands.when_mentioned_or('/', '.', 'c.'), owner_id=503641822141349888, intents=intents)
self.persistent_views_added = False
async def on_ready(self):
if not self.persistent_views_added:
self.add_view(PersistentView())
self.persistent_views_added = True
activity = discord.Game(name="fc.coolmcgames.xyz", type=3)
await self.change_presence(status=discord.Status.online,
activity=activity)
print(f'Signed in as {self.user}')
bot = slash_util.Bot(command_prefix=commands.when_mentioned_or('/', '.', 'c.'), owner_id=503641822141349888, intents=intents)
class SlashCog(slash_util.ApplicationCog):
def __init__(self, bot):
super().__init__(bot)
self.bot = bot
@slash_util.slash_command()
async def hello(self, ctx):
await ctx.send('hi')
bot.add_cog(SlashCog(bot))``` I can't seem to figure out how to add the cog to the PersistantViewBot, could someone help me with this?
intents
not intenes
Can you use hyperlinks inside of a embed title
please read the error carefully
no
Oh ok
oh
omg
From R.Danny;
"[Text To Click](https://www.youtube.com/ \"Hovertext\")"
- Needs to be a full url (http/https)
- Hovertext is optional
- If sent by a bot/user it needs to be in an embed
- If sent in a webhook you can hyperlink raw text cuz fuck being consistent amirite discord
- This only works in the embed description and field value
If you want to hyperlink a title or set_author, you can use theurlkwarg
im sorry gimme a sec
ik
Why does not add the participant to the database specifically to the blacklist
so apparently you can, with the url kwargs - i did not know that o.O
i forgot how to do the hovertext, thanks for showing me
@manic wingU ARE A LITERAL WIZARD
Ahh your working on a chromebook i used to do that untill it ran out of space 😐
@manic wing Did i indent everything right
Darnit
How to make a check that if a person's id is in this key then ...
what
was i right about you being on a chromebook
No
I do not know what is chromebook.
Bro Look my message i was looking for was above yours
I looked and what does it mean?
How does this relate to my question?
this should looking like this?
what?
oh
Traceback (most recent call last):
File "C:\Users\PC\Desktop\Dadudeł Bot\Dadudeł Bot.py", line 17, in <module>
intents.all = True
AttributeError: 'Intents' object attribute 'all' is read-only i got something like that when i turned it on
idk why
Will my discord bot support sql injection if I use mongo db? @pliant gulch
Show the cog file. Looks like you didn’t subclass it correctly
Should be:
class myCog(commands.Cog):
Can anyone tell me why my bot wont run the slash command on Visual Studio Code?
token = '1234567890'
bot = coammnds.Bot(
intents=discord.Intents.all()
)
@bot.slash_command(
name='ping',
description='Returns the bots latency.'
)
async def ping(ctx):
embed = discord.Embed(
color=color,
title='**Ping**',
description='\u200b'
)
await ctx.send(embed=embed)
bot.run(token)```
Try to avoid naming commands and cogs the same thing. I’m assuming there is a naming conflict?
commands.Bot
Is spelled wrong
.
Nope
Add from discord.ext import commands
Same thing
import discord
from discord.ext import commands
from discord.ext import commands, tasks
import asyncio
from itertools import cycle
import os
import json
import random
import datetime
import requests
import aiosqlite
from typing import Text
import aiohttp
import platform
from discord.ext.commands import clean_content
intents = discord.Intents.all()
intents.all= True
bot = commands.Bot(command_prefix="+",intents=intents) what i did wrong?
Add from start to end
that keeps blinding me
Remove intents.all = True
So it's not messy.
Requests is blocking
Don't use it
aiohttp
How do I download it in the terminal?
You don't download anything
but when i did it this still dosent work
Just copy and paste
Okay.
ok
Whats the error?
i mean i need to test it
im abt to just give up on this
ooo it works but it didn't ping owner of the server
i honestly have no clue how to fix this stupid thing
Is there something I need to import for get_channel() , get_guild(), get_role(), etc ?
literally
this close to giving up 🤏
what
i already tried to indent everything and then it had another problem idk what to do what part do u want me to indent
indent the command decorator and the function
@client.event
async def on_message(message):
if ('help' in message.content.lower() and 'staff' in message.content.lower()):
await message.channel.send('Hello')
like this
Do I have to change message.send to something else?
message.channel.send
how would that magically fix it not being able to find the yoga ball command
and if it does istg im gonna flip out
Do you mean indent it inside the class?
yes
There you go
let me get this straight
you want me to indent this py class Ball(commands.Cog, name="Balls"): def __init__(self, bot): self.bot = bot
^^^
Also fix your indents inside of the commands
indent this part ```py
@commands.group(name = "yogaball")
async def yogaball(ctx):
ok
and the other one
and put ctx
you alr have ctx
ok but now its gonna freak out
why
@client.event
async def on_message(message):
if ('help' in message.content.lower() and 'staff' in message.content.lower()):
await message.channel.send('Hello')
replace the context with ctx
Does anyone know why. this event makes my bot stop responding to other commands?
process the commands
My bot literally stops working if i put this in
await client.process_commands(message)
at the end of your event
oh ok
i was gonna say that
Don't create a bot like that
Use actual command decorators
untill my pc decided to just stop functioning lmao
im trying to learn brother, not making a bot yet
This is the wrong way to learn
wdym?
wat outdated
the pass_context is outdated
This code doesn't work on Python (vsc).
from discord.ext import commands
token = 'my_bot_token'
bot = commands.Bot(
intents=discord.Intents.all()
)
@bot.slash_command(
name='ping',
description='Returns the bots latency.'
)
async def ping(ctx):
embed = discord.Embed(
color=color,
title='**Ping**',
description='\u200b'
)
await ctx.send(embed=embed)
bot.run(token)
ok
Whats actual command decorators?
@client.command()
What if the member doesnt do the prefix ?
And its an event?
You need to give a prefix in the bot constructor arguments
Then nothing happens. There is an invoke_without_prefix kwarg if I remember correctly
oh wow, i didn't know that. Let me search that up
Lets see the code
error?
i think i know the issue gimme a min
Also I have no idea why you're putting brackets everywhere
Brackets?
()
Where
In the commands.Bot() statement
he probably using a fork
omg i quit
Hes importing discord
error
That is dpy
py-cord is import discord
wdym
!pypi py-cord
bro i thought it was cuz i didnt add like the info thing for it
Are you using the official dpy or a fork?
idk
@slate swan py-cord is literally discord.py
and this is why i thought it wasnt working
a fork
becuase i didnt put this thing
They don't have documentation. It just links to the dpy docs
in this
sussy i see py-cord's docs
I'm clicking on the link at the bottom. Their pypi page is complete shit tbh. They literally just copied the dpy one while having completely different syntax
same as the other forks
ahh self has to be the first arg if your command is in a cog
yeah
LETS GOOOOO
put self aas the first arg
@wild oak Im guessing you didn't learn python basics before dpy?
These are the types of issues that leads to
fix the indent a bit
bro
where
i tried 😩
welp
So the yogaball command works now
but same error for the help command
lmao
thats because the cog returned a None
Hello given that my bot has several modules(cogs) in it
I want to check if a command was executed from a specific cog, if this is True then # do something.
Is there an event that checks for commands in a specific cog?
I'm using Discord.py
how do i fix that i thought i put the """ thing
@client.event
async def on_message(message):
if message.author == client:
return
if 'help' in message.content.lower():
await message.channel.send('Hello, How can I help you?')
await client.process_commands(message)
The bot reads. its own message and gets stuck in an infinite loop. How do i make the bot not read 'help' in its own message?
I could be wrong here but try to use this code:
if not message.author.bot:
#(everything goes in here)
await self.process_commands(message)
@slate swan
ok lemme try
@slate swan I literally tried to fix it and i cant
put your conditionals in there
it keeps saying the same stupid thing
this is how my help commands set up this is the error and its becuase i added this new command
Your error is because cog is not being recognized as an actual cog.
Clearly indicating a Nonetype which does not have .get_commands()
Check each error and see if you can fix it
Could you show me help.py
thanks
it literally worked untill i made a new cog
do you want to see the new cog?
Yes
Well you seem to know the problem, one of your cogs is not being recognized
Do you know why?
originally i thought this was the problem
becuase i didnt have this in the start
but it wasnt
try doing something
like what a diffrent command
ok
just to see if this works
Works?
self.bot.get_cog(i) without the lower
no parenthesis
trying it
What is the point of doing get_cog here?
oh
I'm guessing he wants to get the cog instance
Bot.cogs is a dict which contains the cogs name as the key and the cog class itself...
OH MY GO
If you want all cogs you can just do for i in self.bot.cogs.values()
I don't really understand the point of get_cog
did it work?
OHHHHH
so... problem
OMG tysm
Thanks
And thank you
no problem
No because you and maybe a few other people are experienced enough to see that because I'm honestly amazed
Im suprised you saw the issue
I'm surprised too
i was really gonna go without a help command 😂
@client.event
async def on_message(message):
if not message.author.bot:
if ('help' in message.content.lower() or 'staff' in message.content.lower()):
await message.channel.send('Hello, This is an automated message. If you are looking for the list of commands: Please do \"-com\".If you\'re looking for help beyond that: respond with yes. If you dont need help and this is a mistake: respond with no.')
try:
reply = await client.wait_for("reply", check = lambda m: m.author == message.author and m.channel == message.channel, timeout = 30.0)
except asyncio.TimeoutError:
await message.channel.send("This conversation will end because you failed to reply.")
else:
if reply.content.lower() == 'yes':
await message.channel.send('What specifically do you need help with?')
elif reply.content.lower() == 'no':
await message.channel.send('Oh no! I\'m so sorry! Hope you are enjoying your time here at LOL.')
else:
await message.channel.send('I cannot understand your reply. Sorry!')
await client.process_commands(message)
anyone know why the bot dont respond even tho i said yes or no?
Does anyone know what is going on here?
@client.event
async def on_member_join(member):
defaultRole = member.guild.get_role(defaultRoleID)
await systemMessagesChannel.send(f"Welcome {member.mention} to the **Noobs Who Code** community, you noob!")
await member.add_roles(member, defaultRole)
Exception:
2021-11-28T02:10:34.927060+00:00 app[worker.1]: Ignoring exception in on_member_join
2021-11-28T02:10:34.928638+00:00 app[worker.1]: Traceback (most recent call last):
2021-11-28T02:10:34.928659+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/nextcord/client.py", line 351, in _run_event
2021-11-28T02:10:34.928660+00:00 app[worker.1]: await coro(*args, **kwargs)
2021-11-28T02:10:34.928667+00:00 app[worker.1]: File "/app/main.py", line 29, in on_member_join
2021-11-28T02:10:34.928668+00:00 app[worker.1]: await systemMessagesChannel.send(f"Welcome {member.mention} to the **Noobs Who Code** community, you noob!")
2021-11-28T02:10:34.928683+00:00 app[worker.1]: AttributeError: 'NoneType' object has no attribute 'send'
What is systemMessagesChannel?
so how does this bot channel work
do i just ask my question and the bot will magically find an answer
systemMessagesChannel = client.get_channel(913090699254190110)
So its saying its None
Is the ID correct?
It wasn't doing this earlier, not sure what I changed... do you know if get_channel() requires a certain import ?
Yes it is
It is working with my on_member_remove() so it can't be that
Can I see the code where its getting the channel?
Can anyone create me a simple ping pong command with slash commands?
Every time I try and build one it never works.
YouTube tuts are outdated.
Ok I am not doing this right, so it looks like I cant use get_channel, get_role and things like that outside of a function. Do you know a way I can define my systemMessagesChannel without redefining it everytime I wanna use it ?
.
One sec, I gotchu
Send the code
Just deleted it bc I gave up.
from discord.ext import commands
client = commands.Bot(command_prefix="$") # you can define your prefix here lol
@client.command()
async def ping(ctx):
await ctx.message.channel.send("pong")
client.run(put token here)
(with slash commands?)
Read the docs
@client.event
async def on_message(message):
if not message.author.bot:
if ('help' in message.content.lower() or 'staff' in message.content.lower()):
await message.channel.send('Hello, This is an automated message. If you are looking for the list of commands: Please do \"-com\".If you\'re looking for help beyond that: respond with yes. If you dont need help and this is a mistake: respond with no.')
try:
reply = await client.wait_for("reply", check = lambda m: m.author == message.author and m.channel == message.channel, timeout = 30.0)
except asyncio.TimeoutError:
await message.channel.send("This conversation will end because you failed to reply.")
else:
if reply.content.lower() == 'yes':
await message.channel.send('What specifically do you need help with?')
elif reply.content.lower() == 'no':
await message.channel.send('Oh no! I\'m so sorry! Hope you are enjoying your time here at LOL.')
else:
await message.channel.send('I cannot understand your reply. Sorry!')
await client.process_commands(message)
anyone know why this isnt working?
This should tell you all you need to know https://pythonrepo.com/repo/eunwoo1104-discord-py-slash-command
!d discord.Client.latency then multiply it by 1000
property latency: float```
Measures latency between a HEARTBEAT and a HEARTBEAT\_ACK in seconds.
This could be referred to as the Discord WebSocket protocol latency.
Creating a slash command will be different depending on which library you're using
What do you mean not working?
idk where the bot stops working but if my input is 'yes' or 'no' it doesn't do anything
Also no need for the brackets in the if statement
ok
I haven't worked with wait_for you could put print statements along your code to see where it stops though
perfect, let me try
ig there's something wrong w
try:
reply = await client.wait_for("reply", check = lambda m: m.author == message.author and m.channel == message.channel, timeout = 30.0)
because after 30 seconds the bot just says its gonna end the conversation bc i failed to reply even tho i replied
Is reply a valid event?
Nice
Hey so I am trying to get a role object so I can add it to a user.
Code:
@client.event
async def on_member_join(member):
defaultRole = member.client.get_role(defaultRoleID)
systemMessagesChannel = client.get_channel(systemMessagesChannelID)
await systemMessagesChannel.send(f"Welcome {member.mention} to the **Noobs Who Code** community, you noob!")
await member.add_roles(defaultRole)
Exception:
2021-11-28T02:40:44.585128+00:00 app[worker.1]: Ignoring exception in on_member_join
2021-11-28T02:40:44.585562+00:00 app[worker.1]: Traceback (most recent call last):
2021-11-28T02:40:44.585583+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/nextcord/client.py", line 351, in _run_event
2021-11-28T02:40:44.585584+00:00 app[worker.1]: await coro(*args, **kwargs)
2021-11-28T02:40:44.585586+00:00 app[worker.1]: File "/app/main.py", line 23, in on_member_join
2021-11-28T02:40:44.585586+00:00 app[worker.1]: defaultRole = member.client.get_role(defaultRoleID)
2021-11-28T02:40:44.585606+00:00 app[worker.1]: AttributeError: 'Member' object has no attribute 'client'
Im not sure how to get the role properly
from nextcord.ext import commands
bot = commands.Bot(command_prefix= "??")
bot.command()
async def ping(ctx):
await ctx.send("Pong!")
bot.run("*token*")```
Could someone tell me whats wrong with this code?
python.exe c:/Users/Windows/OneDrive/Desktop/Bot/main.py
Ignoring exception in command None:
nextcord.ext.commands.errors.CommandNotFound: Command "ping" is not found
it gives me this error
i really wanna get this code error sorted i need somones help
@client.event
async def on_raw_reaction_add(payload):
if payload.member.bot:
pass
else:
with open('reactrole.json') as react_file:
data = json.load(react_file)
for key, value in data:
if value['emoji'] == payload.emoji.name:
role = discord.utils.get(client.get_guild(
payload.guild_id).roles, id=['role_id'])
await payload.member.add_roles(role)
I tried to add the bot to my server, not sure what happened but it did not seem to work?
Ignoring exception in on_raw_reaction_remove
Traceback (most recent call last):
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\thoma\Desktop\discord.py\python\bot.py", line 38, in on_raw_reaction_remove
for key, value in data:
ValueError: too many values to unpack (expected 2)
Ignoring exception in on_raw_reaction_add
Traceback (most recent call last):
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\thoma\Desktop\discord.py\python\bot.py", line 76, in on_raw_reaction_add
for key, value in data:
ValueError: too many values to unpack (expected 2)```
Im not sure if this is your error, but I don't know if you can have two characters for your prefix. I could be wrong but maybe try it with one "?" maybe?
Oh I know your problem
fr? whats it
Make it
@bot.command()
You forgot the "@"
Anyone please?
Lol thank you.. I think ??
Anyone plz?
How did you add your bot?
christian
Hello there
do you know how to make cogs? Ive tried it a few times now and ive failed
How do you guys make like this link? https://discord.gg/python
I do not unfortunately, not that experienced myself
I'll send you a vid
Wdym "like this"
Vanity url
like have ur invite link have ur discord server name link
Meaning?
go to discords developer portal, give ur bot the admin rights and copy the link i think
You need server boosted to the highest teir
After a certain amount of boosts the server owner can change the invite link for the server
ive looked at them myself too but it didnt work
I followed this tutorial for making a music bot, it uses cogs and it's what helped me start with cogs
TODAY we’re making a budget Rythm as easily as possible. Enjoy!
Thanks (for non copyright music):
🍪 Soundcloud : https://soundcloud.com/lukrembo
⭐️ Twitter : https://twitter.com/LuKremBo
😀 Instagram : https://www.instagram.com/lukrembo
✉️ Email : Lukrembo@gmail.com
----------------...
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
wtf looool
could you explain to me how to do it? like its prolly just @bot.load_extension(filename)
read smartass
Well he is talking about using it for cogs not the actual bot though?
or some like that
Still sharing how to make a music bot
they just helpin me wtf
Alright
Id take the topic to DMs tbh
No there is a section in the video in main.py that's like ```python
import mycog1
import mycog2
cogs = [mycog, mycog2]
bot = commands.Bot(command_prefix="!")
for i in range(len(cogs)):
cogs[i].setup(bot)
I don't fully understand it yet but this is how it was implemented, and it works
Thats not ideal
hm alright i think i understand it
So is anybody able to help ?
You can loop through a directory where you store all your cogs and load them automatically instead of doing it manually
wdym
show us how please
thats like the only thing i need rn
ion wanna do everything in the main file
yeah I'm interested in how to do that now
This goes against my rule of spoon feeding but sure
omg
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
client.load_extension(f'cogs.{filename[:-3]}')
this guy
I feel like some people just need to see how to stuff just saying
ight thanks
edit client to what ever you defined your bot constructor as
I think its just client.get_role()
Not sure
Ok trying that rn
With this bit os.listdir('./cogs') you would change 'cogs to what ever the folder name is that you stored your cogs in
How can I find the code for these emojis: ✅ ❌
If the cogs folder is not in the same directory your main.py file is in you're going to have to provide a full path
thats ugly
Pretty sure its just <:name of emoji:id> but Im not sure
!d pkgutil.iter_modules
pkgutil.iter_modules(path=None, prefix='')```
Yields [`ModuleInfo`](https://docs.python.org/3/library/pkgutil.html#pkgutil.ModuleInfo "pkgutil.ModuleInfo") for all submodules on *path*, or, if *path* is `None`, all top-level modules on `sys.path`.
*path* should be either `None` or a list of paths to look for modules in.
*prefix* is a string to output on the front of every module name on output.
Note
Only works for a [finder](https://docs.python.org/3/glossary.html#term-finder) which defines an `iter_modules()` method. This interface is non-standard, so the module also provides implementations for [`importlib.machinery.FileFinder`](https://docs.python.org/3/library/importlib.html#importlib.machinery.FileFinder "importlib.machinery.FileFinder") and [`zipimport.zipimporter`](https://docs.python.org/3/library/zipimport.html#zipimport.zipimporter "zipimport.zipimporter").
Changed in version 3.3: Updated to be based directly on [`importlib`](https://docs.python.org/3/library/importlib.html#module-importlib "importlib: The implementation of the import machinery.") rather than relying on the package internal [**PEP 302**](https://www.python.org/dev/peps/pep-0302) import emulation.
2021-11-28T02:57:11.670918+00:00 app[worker.1]: Ignoring exception in on_member_join
2021-11-28T02:57:11.671346+00:00 app[worker.1]: Traceback (most recent call last):
2021-11-28T02:57:11.671368+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/nextcord/client.py", line 351, in _run_event
2021-11-28T02:57:11.671368+00:00 app[worker.1]: await coro(*args, **kwargs)
2021-11-28T02:57:11.671375+00:00 app[worker.1]: File "/app/main.py", line 22, in on_member_join
2021-11-28T02:57:11.671375+00:00 app[worker.1]: defaultRole = client.get_role(defaultRoleID)
2021-11-28T02:57:11.671391+00:00 app[worker.1]: AttributeError: 'Bot' object has no attribute 'get_role'
Welp worth a try
You may just put \ in front of emoji
Like \
These don't have Ids i think. I didn't find them atleast
\✅
so.. this?
\❌
Theres really no point to using this. It complicates things for no reason
For beginners my method is just fine
Yes
it doesn't, it's a two line code
Nope, emoji argument must be str, Emoji, or Reaction not NoneType
bot.py lines 26 to 27
for cog in pkgutil.iter_modules(["cogs"]):
bot.load_extension(f"cogs.{cog.name}")```
Mmm weird, maybe look on the docs?
Haha
It works to me
So reducing the code by 1 line really matters that much?
it's not getrole, it's testRole = discord.utils.get(ctx.guild.roles,name=<role name>,id = <id>), u can either use name or I'd but don't use both at same time
readability matters
Thats why simplicity is important
yes
;(
Your method may be simple for you but for someone who has never heard of pkgutil its not
for this u need to import discord.utils get function, from discord.utils import get
Traceback (most recent call last): File "c:\Users\Windows\OneDrive\Desktop\Bot\main.py", line 12, in <module> bot.load_extension(f'cogs.{filename[:-3]}') File "C:\Users\Windows\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\bot.py", line 733, in load_extension self._load_from_module_spec(spec, name) File "C:\Users\Windows\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\bot.py", line 678, in _load_from_module_spec raise errors.ExtensionFailed(key, e) from e nextcord.ext.commands.errors.ExtensionFailed: Extension 'cogs.mainhelp' raised an error: CommandRegistrationError: The command help is already an existing command or alias. PS C:\Users\Windows\OneDrive\Desktop\Bot>
Anyone got an idea of what this means?
pkgutil is a useful built-in module, they should know about it, there's no fix time for beginners to know them
that command already exists
but it doesnt, thats a file i made in a folder called cogs
so basically discord.py made this update abt the help cmd every bot has
I think thats a different way
im not using discord.py lol im using nextcord
but works
Same thing essentially
I have never seen anyone use that module. I doubt if its that useful I never would of heard about it
Yep
because they never heard of it, this is one of things why using cogs is so easy
Can someone explain to me how to use the get_role() because all the docs tells me is that I need to put an ID in as an argument but I dont know if I should be doing member.get_role() or whatever lol
``PS C:\Users\Windows\OneDrive\Desktop\Bot> & C:/Users/Windows/AppData/Local/Programs/Python/Python39/python.exe c:/Users/Windows/OneDrive/Desktop/Bot/main.py
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Windows\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\core.py", line 720, in _parse_arguments
next(iterator)
StopIteration
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Windows\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Windows\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\bot.py", line 1035, in on_message
await self.process_commands(message)
File "C:\Users\Windows\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\bot.py", line 1032, in process_commands
await self.invoke(ctx)
File "C:\Users\Windows\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\bot.py", line 995, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Windows\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\core.py", line 887, in invoke
await self.prepare(ctx)
File "C:\Users\Windows\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\core.py", line 821, in prepare
await self._parse_arguments(ctx)
File "C:\Users\Windows\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\core.py", line 722, in _parse_arguments
raise nextcord.ClientException(f'Callback for {self.name} command is missing "ctx" parameter.')
nextcord.errors.ClientException: Callback for helpme command is missing "ctx" parameter.``
Bro what?
it doesnt make sense
where am i missing the ctx
the first argument should be "self" and ctx second
fixxed it. Yeah i figured thanks. Could you explain to me what self does?
that is the instance of the class
every method's first parameter is the instance of the class
staticmethod dont need it tho but lets not talk about them
it can be named anything, but you should name it self
u can't get a role from a member ig but u can add role to the member by doing "add_role" and vice versa by "remove_role"
but u can get a role from the guild
!e
class Foo():
def __init__(self):
self.name = "myxi"
def method(self, name):
print(self.name)
self.name = name
print(self.name)
foo = Foo() #this is our instance, doing this will call __init__ method. there are a few other methods that get called too but this is the one which is mostly useful
foo.method("prime")
that was a pain
@sullen shoal :white_check_mark: Your eval job has completed with return code 0.
001 | myxi
002 | prime
I dont think you understand my question
tbh I would suggest u to use utils instead of trying hard the get_role
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
utils method is slow, you shouldn't stick with that
Again, I know what the arguments I need to put are its just I dont know what to put before the get_role()
So how do I do this?
commands.Context returns the guild with one of it's attributes, discord.Message returns it with one of its attributes as well
you may check their docs
But do I put like.. client.get_role() ?
Idk where you want me to check
what is your confusion
Ok so I have a on_member_join().
I need to give a member a role inside of that function.
In order to do this I believe I need a role object so I can use add_roles().
I need to know what to put before the get_role(roleID) in this case.
I tried client.get_role(roleID) but that did not seem to work.
I don't know what exactly to put in this case.
!d discord.Member.guild
The guild that the member belongs to.
member.guild is a discord.Guild instance
this event's first parameter (except the class instance) is discord.Member instance
The first and the only param*
@client.command()
async def testing(ctx):
embed1 = discord.Embed(
title="",
description=
f"Embed1",
color=discord.Color.purple())
embed2 = discord.Embed(
title="",
description=
f"Embed2",
color=discord.Color.purple())
await ctx.send(embed=embed1, embed=embed2)``` How would I send both the embeds?
await ctx.send(embeds=embed1, embed2)``` Doesn't seem to work, but I probably misunderstood you
send(embeds=[embed1, embed2])
Ahh, thank you!
@client.event
async def on_message(message):
if not message.author.bot:
if 'help' in message.content.lower() or 'staff' in message.content.lower():
embed = discord.Embed(description = '**__Hello, This is an automated message.__** \n- If you are looking for the list of commands: Please do \"-com\". \n- If you\'re looking for help beyond that: respond with \"yes\". \n- If you dont need help and this is a mistake: respond with \"no\".')
await message.channel.send(embed = embed)
How do i make the bot respond in a different channel?
!d discord.TextChannel.send
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
[perfect thanks
you need an instance of TextChannel, not the class itself.
discord.Message.channel returns it
thats why you did message.channel.send because
message which is discord.Message has an attribute channel which returns it
!d discord.ext.commands.Bot.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
!d discord.Guild.get_channel
get_channel(channel_id, /)```
Returns a channel with the given ID.
Note
This does *not* search for threads.
wdym it's slow
It takes too much time
it doesnt
okay so ive added a button to my bot, and i wanted to know if its possible to show this message "Coming!" as an Embed and not just a normal message (nextcord)
Breg in small operations it doesn't, but when your bot gets bigger and stuff, it will start taking
k
Just use the embed kwarg?
but where tho
send_message()
embedR = discord.Embed(title="title", description="smh")
under the await Interaction right?
No, inside it 🤦
oh yeah saw it but whenever i do embed = discord.Embed(title..etc)
it says discord is not defined
Then do nextcord.Embed
alr thanks
thanks
PS C:\Users\Windows\OneDrive\Desktop\Bot> & C:/Users/Windows/AppData/Local/Programs/Python/Python39/python.exe c:/Users/Windows/OneDrive/Desktop/Bot/cogs/mainhelp.py
File "c:\Users\Windows\OneDrive\Desktop\Bot\cogs\mainhelp.py", line 12
await interaction.response.send_message(embedR = nextcord.Embed(title="title", description="smh")), ephemeral=True)
^
SyntaxError: cannot assign to await expression
PS C:\Users\Windows\OneDrive\Desktop\Bot>
now how would i fix this
question how can you make the !e command from the python bot?
check the source code
someone help me please
good idea
!src e
Run Python code and get the results.
thx
anyone?
fixed it
it works thanks a lot @maiden fable
next question, is there a way i could add buttons to a message sent from the bot because the user clicked on a button?
does someone have a script that makes bots leave all the server its in
i only found out how to do it when someone messages something
!d discord.Client.guilds
property guilds: List[discord.guild.Guild]```
The guilds that the connected client is a member of.
!d discord.Guild.leave
await leave()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Leaves the guild.
Note
You cannot leave the guild that you own, you must delete it instead via [`delete()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.delete "discord.Guild.delete").
how to resolve this?
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Windows\Desktop\MyBot.py", line 41, in on_message
if client.is_voice_connected(message.server):
AttributeError: 'Client' object has no attribute 'is_voice_connected'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Windows\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Windows\Desktop\MyBot.py", line 85, in on_message
await client.send_message(message.channel, "Error: [{error}]".format(error=e))
AttributeError: 'Client' object has no attribute 'send_message'```
You’re using a tutorial video in YouTube?
no
anybody know the reason of this error?
disnake.ext.commands.errors.UnexpectedQuoteError: Unexpected quote mark, '"', in non-quoted string
It’s severely outdated code.
Can someone tell me how did the time thing in the footer update automatically
And how is it synced to my timezone when it looks different to other people
It should just be await message.channel.send(“Error: [{error}]”.format(error=e))
!d discord.ext.commands.errors.UnexpectedQuoteError
exception discord.ext.commands.UnexpectedQuoteError(quote)```
An exception raised when the parser encounters a quote mark inside a non-quoted string.
This inherits from [`ArgumentParsingError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.ArgumentParsingError "discord.ext.commands.ArgumentParsingError").
looks like the command arguments has a "
And message is not even edited
Hey yall how can i make my bot send a perfect embed from a message that comes from a button? I cant see finding out how
Define the embed first then send it with the interaction response…
Wow you the Developer of slot bot?
how can i fix it?
nah im making a bot that explains what each bot does
Bruh
its just for training i aint that good at python so i gotta work on something
try making it a keyword only argument (eat all the text the user provides)
AttributeError: 'Client' object has no attribute 'is_voice_connected'
AttributeError: 'Client' object has no attribute 'send_message'```
client object?
what
Can someone please tell me this
i used *args
thats not keyword only argument
yeah ik
ctx, *, arg
If you find out lemme know 😄
im going to try it
Bruh
command(ctx, arg, arg2): pass
if you do the command smth like this,
.command "hello world oof i" hello
first arg will contain the content inside the quotes and the second one hello
how can i fix an error if it says ctx is not defined?
Pass an aware datetime object into timezone kwarg of embed
And it won't be updated
thanks brother
It should be updated automatically by discord...
And won't be synced to other member's timezones
I guess there was some change in the api recently requiring you to pass .... maybe utc aware object iirc
what datetime object did you pass?
Well I got the answer already
`text_here` -> text_here
Bruh just use `some_text`
the text comes like: text here but it is not white, it is grey(the font in the image is white)
`by doing this`
When it will be inside an embed it will look white
Do you mean to bold it too? Try **`text_here`**
yes that works
Does anyone know what i should replace author with in the m.channel == ?
its usually the channel that the message is going to be read, i want to set to to author.dms
lemme try
dm = await message.author.create_dm()
m.channel == dm
whats bots you guys making
dm = await message.author.create_dm()
and just set m.channel = dm
Yes u can do that
?
Umm no, comparisons first check if the classes are instances of a common class
dm = await message.author.create_dm()
and just set m.channel = dm
this worked,
Instead do m.channel == user.dm_channel
Why do you need to comsume a request ...?
is that bad in any way?
Umm sorry it's fine.. It first checks if dm_channel exists
So you're good with it
Umhmm
1 thing, if you're free
@slate swan
Sure
so this is my code:
@client.event
async def on_message(message):
if not message.author.bot:
if 'help' in message.content.lower() or 'staff' in message.content.lower():
dm = await message.author.create_dm()
embed = discord.Embed(description = f'**__Hello {message.author.mention}, This is an automated message.__** \n- If you are looking for the list of commands: Please do \"-com\". \n- If you\'re looking for help beyond that: respond with \"yes\". \n- If you dont need help and this is a mistake: respond with \"no\".')
await dm.send(embed = embed)
try:
reply = await client.wait_for('message', check = lambda m: m.author == message.author and m.channel == dm, timeout = 30.0)
except asyncio.TimeoutError:
reply_embed = discord.Embed(description = 'This conversation will end because you failed to reply.')
await message.author.send(embed = reply_embed)
else:
if reply.content.lower() == 'yes':
embed = discord.Embed(description = 'What specifically do you need help with?')
await message.author.send(embed=embed)
elif reply.content.lower() == 'no':
embed = discord.Embed(description = 'Oh no! I\'m so sorry! Hope you are enjoying your time here at DSRP.')
await message.author.send(embed=embed)
elif reply.content.lower() == '-com':
embed = discord.Embed(description = 'There\'s your list of commands')
await message.author.send(embed=embed)
else:
embed = discord.Embed(description = 'I cannot understand your reply. Sorry!')
await message.author.send(embed = embed)
await client.process_commands(message)
when a user inputs -com, it responds with a custom client.group and the bot basically outputs the group + "here's your list"
How can i fix this error? "ctx" is not defined.
Show entire command
Define it
the bot is somehow printing that list the commands command in dms and hhanding me a huge error
Umm also, what is client.group?
its working but its giving me a huge error
Error?
a command list i made
lemme send error
oh okay
Either make your bot check the added bot's permissions and ping a staff whose online
Im working on a bot that basically explains the economy systems of other bots.
and i want to have a button to the message that came from a button if yk what i mean
Ignoring exception in command com:
Traceback (most recent call last):
File "/home/lol/miniconda3/lib/python3.9/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/lol/bot.py", line 27, in com
await ctx.message.delete()
File "/home/lol/miniconda3/lib/python3.9/site-packages/discord/message.py", line 1023, in delete
await self._state.http.delete_message(self.channel.id, self.id)
File "/home/lol/miniconda3/lib/python3.9/site-packages/discord/http.py", line 248, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50003): Cannot execute action on a DM channel
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/lol/miniconda3/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/lol/miniconda3/lib/python3.9/site-packages/discord/ext/commands/core.py", line 1353, in invoke
await super().invoke(ctx)
File "/home/lol/miniconda3/lib/python3.9/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/lol/miniconda3/lib/python3.9/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: Forbidden: 403 Forbidden (error code: 50003): Cannot execute action on a DM channel
its working but its handing me this error, should i be worried?
Your function Sbdrugs, doesnt have a ctx argument
oh bruh im stupid
thanks a lot
Its okay, dont be like that
def stickbug_vid(url, link):
endpoint=neko_base+"stickbug&url="+str(url)
link[0]=(requests.get(endpoint).json()["message"])
@Blank.command(aliases=["sb", "stb"])
async def stickbug(ctx, user: discord.Member=None):
await ctx.message.delete()
await ctx.channel.send("It will take a little bit of time", delete_after=2.0)
if user is None:
user=ctx.message.author
url=[None]
t1=Thread(target=stickbug_vid, args=((user.avatar_url_as(format="png"), url))).start()
t1.join()
try:
file=io.BytesIO(requests.get(url[0]).content)
await ctx.channel.send(file=discord.File(file, 'stickbug.mp4'))
except Exception:
await ctx.channel.send(url)```
Error: Nonetype object has no attribute join
You're trying to delete user's message in their dm
You can't, as the error says
ahh okay understood
i'll just ignore it lol
okay, so now it almost works fine its just that there isnt a button on the last message.
Just remove the .delete() call, or suppress the error so that it don't affect anything else
1. Drugs
There can't be a button on an ephemeral message
how would i suppress the error?
ah alright
Wait.....nqn does that
Does it?
i cant really delete the call bc its it helps organize bot commands chat in main server
Lemme see
Your line 27 in bot.py... remove that line if you don't need it,... or use contextlib.suppress()
!d contextlib.suppress
contextlib.suppress(*exceptions)```
Return a context manager that suppresses any of the specified exceptions if they occur in the body of a `with` statement and then resumes execution with the first statement following the end of the `with` statement.
As with any other mechanism that completely suppresses exceptions, this context manager should be used only to cover very specific errors where silently continuing with program execution is known to be the right thing to do.
For example...
ill try if it works without ephemeral on
where would contextlib.suppress() go?
@maiden fable yes nqn uses buttons on them too
Can I see a pic?
with contextlib.suppress(Exception):
# do whatever can error and you need to suppress it
ok
Oh, hmm sorry my bad then
Lmao, your about meee so cool
Haha thanks
...
also, is there any way for the bot to purge the conversation in dms once its done?
@maiden fable @upbeat otter sorry for the ping but do yall have any idea perhaps
Try passing the view with button as a view= kwarg
alr
No
It can only purge it's own messages
but not the users'
sounds good
sorry to ask this but what was a kwarg again?
!args-kwargs
*args and **kwargs
These special parameters allow functions to take arbitrary amounts of positional and keyword arguments. The names args and kwargs are purely convention, and could be named any other valid variable name. The special functionality comes from the single and double asterisks (*). If both are used in a function signature, *args must appear before **kwargs.
Single asterisk
*args will ingest an arbitrary amount of positional arguments, and store it in a tuple. If there are parameters after *args in the parameter list with no default value, they will become required keyword arguments by default.
Double asterisk
**kwargs will ingest an arbitrary amount of keyword arguments, and store it in a dictionary. There can be no additional parameters after **kwargs in the parameter list.
Use cases
• Decorators (see !tags decorators)
• Inheritance (overriding methods)
• Future proofing (in the case of the first two bullet points, if the parameters change, your code won't break)
• Flexibility (writing functions that behave like dict() or print())
See !tags positional-keyword for information about positional and keyword arguments
Lol
I would suggest you'd learn vasic Python brfore approaching the discord.py library, as it is a complicated that involved a lot of advanced Python library
i am learning both, its just that sometimes i forget some easy things
do you know python
you're mutating a list instead of returning
huh?
def stickbug_vid(url, link):
endpoint=neko_base+"stickbug&url="+str(url)
link[0]=(requests.get(endpoint).json()["message"])
just, return?
how can I, i never used aiohttp for this function
read the aiohttp quickstart docs
they will tell you all you need to know about using it
!e```py
from threading import Thread
def function(arg, s):
s[0]=arg
t=[None]
a=Thread(target=function, args=(3, t))
a.start()
a.join()
print(t[0])```
\🤔
this seems like a "why use threading" moment of overcomplication
why is it not executing??
🤷♂️
!e```py
from threading import Thread
def function(arg, s):
s[0]=arg
t=[None]
a=Thread(target=function, args=(3, t))
a.start()
a.join()
print(t[0])```
use aiohttp
hmmm...
Why are you using threading with an asynchronous environment
multiprocessing 

