#discord-bots
1 messages · Page 444 of 1
so your line would be
last_msg = ctx.channel.last_message
@bot.command()
async def react(ctx, chat:discord.Message, emoji):
try:
if emoji is None:
await ctx.send(f":exclamation: {ctx.author.mention} Please Specify the Emoji which you want to React")
else:
message = chat
await message.add_reaction(emoji)
except commands.errors.MessageNotFound:
last_msg = ctx.channel.last_message
await last_msg.add_reaction(emoji)
code
but then also message not found error :/
what did you type in discord?
is there a way to make it so it doesnt matter if the prefix used is e! or E!, as of now only e! works py client = commands.Bot(command_prefix="e!", intent = discord.Intents.all(), activity=discord.Activity( type=discord.ActivityType.playing, name="with dough", status=discord.Status.online ))
then you use your own command wrong
oh
um
a solution would be to switch chat with emoji
in the command's arguments
yes
oo i have little bit same command :/
@bot.command()
async def tell(ctx, channel: Optional[discord.TextChannel]=None, *, msg):
if channel is None:
channel = ctx.channel
await channel.send(msg)
what does that have to do with anything
oof
I would switch chat and emoji
and remove the whole try-except
nvm
but first check if chat is None
so like
@bot.command()
async def react(ctx, emoji, chat: discord.Message=None):
try:
if emoji is None:
await ctx.send(f"❗ {ctx.author.mention} Please Specify the Emoji which you want to React")
else:
message = chat
await message.add_reaction(emoji)
except commands.errors.MessageNotFound:
last_msg = ctx.channel.last_message
await last_msg.add_reaction(emoji)
ooooops
then check if chat is None
hm
chat = ctx.channel.last_message-1 ??
no
:/
why? python TypeError: add_field() takes 1 positional argument but 3 were given when python embed.add_field(f'{message.author.name} has been muted', 'They were being very toxic in this message: **{message.content}**')????
it takes name and value kwargs
add_field(name=, value=)
oh, ok, thx!
!d discord.Embed.add_field
add_field(*, name, value, inline=True)```
Adds a field to the embed object.
This function returns the class instance to allow for fluent-style chaining.
i know, i didnt think that i had to do name = tho
deleting your own message before defining last_message would solve this
I don't know if you want to change your command
oo
or find another way to not need to delete your message
😕
what does that mean
put
await ctx.message.delete()
above
chat = ctx.channel.last_message
and see if that's okay for you
k :/
probably, since there's no point of the react command if they see who used it
buttons? the interaction yeah they're cool
yeah
but it is useful in polls :/
I am confused:python muted[message.author.id] = 300
TypeError: 'Role' object does not support item assignment```
polls?
what are you trying to do
like quiz which have mcq
mhm
add a value of 300 do an empty dictionary i created(muted) with the key of the id of the message author
Can you show your full code?
ok
but you also have a role named muted
as I see
it is not working :/
show what you did
sorry
I'm not sure what the chat param is for
:/
because it should always react no matter what
k
so no else
i used this cuz if a member will not specify the emoji bot should tell him to specify :/
yeah, but if the emoji isn't None, it won't access that statement
it should work the opposite way
That " :/ " is really bothering me.
why does my discord.py file close instantly
me too lmao
oops srry
@client.command()
async def ticket(ctx):
guild = ctx.guild
member = ctx.author
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
guild.me: discord.PermissionOverwrite(read_messages=True),
member: discord.PermissionOverwrite(read_messages=True)
}
channel = await guild.create_text_channel(f"{ctx.author.name} `s ticket", overwrites=overwrites)
await ctx.send(f"Your ticket has been created at {channel.mention}")
ticket = discord.Embed(title = "KATSA TICKETS!", description = f"Hello {ctx.author.mention} our staff will be with you soon!", color = discord.Colour.random())
ticket.set_footer(text="Ticket system created by katsa")
close = discord.Embed(title = "Your ticket is being closed", color = discord.Colour.random())
close.set_footer(text="Ticket system created by katsa")
await channel.send(
embed = ticket,
components = [
Button(style = ButtonStyle.red, label = "Close")
]
)
while True:
event = await client.wait_for('button_click')
label = event.component.label
if label == "Close":
await event.respond(type = 4, content = "Deleting your channel...")
await channel.delete()``` hey can anyone help me ? it deletes only the first ticket that i create, in the other ones it said . uknown channel
when I answer and I get an :/, I think I said something wrong
again same problem
no i never meant that srry
Remove while True.
yes
did you pass in a wrong id?
Try to print chat.
Hello, how can I do something when someone dm my bot? I tried this but the bot is spamming me the mesage
@bot.event
async def on_message(message):
if not message.guild:
await message.channel.send("This is a dm")```
ah
if message.author.bot: return
at the very start 😄
Guys, why am i getting an error, extension "dismusic" could not be loaded
😂 I'm so dumb thank you
it is fine 😄
can I see the error?
is it already loaded?
just a minute
why is this not happenening every second?```python
@tasks.loop(seconds=1)
async def checks():
guild = bot.get_guild(861260736457998346)
mute = guild.get_role(883380167865667644)
print(muted)
for member, secsLeft in muted.items():
mem = bot.get_user(member)
if secsLeft == 0:
mem.remove_roles(mute)
del muted[member]
else:
muted[member] -= 1
print('secs left of mute:', secsLeft)
print('starting checks!')
checks.start()```
Is there an error?
await remove_roles?
yea
and isn't this API spamming?
Also yeah 
but that should have errored out
Indeed it is
@maiden fable
Yes. That's considered API abuse. Even if it's used only for you.
You have a cog named "dismusic" that couldn't be loaded.
ohh, but i am using a lava link....
client.lava_nodes = [
{
"host": "lava.link",
"port": 80,
"rest_url": f"http://lava.link:80",
"identifier": "MAIN",
"password": "Anything",
"region": "india"
}
]
@client.event
async def on_ready():
print('Logged in as {0.user}'.format(client))
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="One Piece"))
try:
client.load_extension("dismusic")
client.load_extension("dch")
except Exception as t1:
print(t1)
while True:
await asyncio.sleep(10)
with open("spam.txt", "r+") as file:
file.truncate(0)
but thats because there is no bot.wait_until_ready()
then where?
oh
and why is there a while True deleting everything from a file every ten seconds
lmao
pretty sure that blocks the entire code
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
ytdl?
oh, the cog's name is dismusic
oh....
thnx
actually the code and everything got duplicated
so it was giving an error @lament mesa thnx bro u best helper arround here like @slate swan @spring flax @maiden fable @waxen granite
thnx boiz
Uhhh, did you just ping random people....?
that isnt ytdl
it still breaks the tos
try:
pages = utils.DetailedPages(self.bot, message=ctx.message, entries=entries)
await pages.paginate()
except: #utils.CannotPaginate as e:
await ctx.send("meh")
#await ctx.send(str(e))
```all it sends is
raise e.
we dunno what you're trying to do
entry = {
'title': 'Top {} Osu scores for {}'.format(limit, member.display_name),
'fields': [
{'name': 'Artist', 'value': m.artist},
{'name': 'Title', 'value': m.title},
{'name': 'Creator', 'value': m.creator},
{'name': 'CS (Circle Size)', 'value': m.diff_size},
{'name': 'AR (Approach Rate)', 'value': m.diff_approach},
{'name': 'HP (Health Drain)', 'value': m.diff_drain},
{'name': 'OD (Overall Difficulty)', 'value': m.diff_overall},
{'name': 'Length', 'value': m.total_length},
{'name': 'Score', 'value': i.score},
{'name': 'Max Combo', 'value': i.maxcombo},
{'name': 'Hits',
'value': f"{i.count300}/{i.count100}/{i.count50}/{i.countmiss} (300/100/50/misses)",
"inline": False},
{'name': 'Perfect', 'value': "Yes" if i.perfect else "No"},
{'name': 'Rank', 'value': i.rank},
{'name': 'PP', 'value': i.pp},
{'name': 'Mods', 'value': str(i.enabled_mods)},
{'name': 'Date', 'value': str(i.date)}
]
}
entries.append(entry)
```tryna get these scores as embeds
raise e```
except Exception as e:
await ctx.send("meh")
raise e
n send u tht?
is this a json?
I'm not familiar with these
use a database anyways

iz just a dictionary
using dictionary as a database?
idk abcd of database so u pretty much are making me blinking rn
What is utils?
And whatever it is, it does not have an attribute DetailedPages.
figured as much...but how do i correct it?
Well, I cannot really help you since I don't know what is utils.
aighty...
Is it discord.utils or some third party package?
gimme a sec
why .format and not f strings
No its apart of discord.py
Not in the documentation but there is some methods of it ig
!d discord.utils.get
discord.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Examples
Basic usage...
yes you need discord utils for certain things
i just dumped that idea, i am making my own cmds
what
use f strings then
saves time and much easier
i use f strings, that was from a tutorial
o
i mean i want it to embed them scores..wen i run the command for multiple scores
I don't think discord.utils has any thing such as DetailedPages
Are you getting two modules mixed up or something?
Hey guys i stucked at developing a simple bot. I want to create a Bot which makes automatic reactions on any message in specific channel. I'm using microsoft visual studios with python. Every time i want to run and debug the bot there comes the message no module named x. Can you help me?
m not shore tbh coz i got this cog wid basic osu commands in github....n changed stuffs to get it working...but nawp this is itching under my skin rn
wtf is happening idk
Then whichever github repo you got the command from probably has a utils module its using
Perhaps check their repo and look for a file called utils.py or something
me?
my code is orignal
so im trying to get stuff out of a .json file and then load it but i keep on getting this
print('[INFO] Loading DATA')
with open("config.json") as file:
info = json.load(file)
token = info["token"]
welcomechannel = info["welcomechannel"]
giveaway1 = info["giveaway1"]
giveaway2 = info["giveaway2"]
giveaway3 = info["giveaway3"]
chat = info["chat"]```
the json doesn’t contain a "giveaway1" key
oki
anyone
I wasn't responding to you
?
sorry
a pretty basic error
you should be able to know what’s wrong
i am not able to
thats why i asked
then i suggest you go back to python basics
pls tell me
discord.py is not for beginners
{
"welcomechannel":"877023857897275453", "token":"", "giveaway1":"877748965762826240","giveaway2":"","giveaway3":"","chat":"877023857897275453"
}
``` but it does
pls
Can you help me?
print info
install it
can u please help
py -m pip install discord.py
Learn python
pip3 install discord.py
I have seen that video lol u skidded all the code of it
@slate swan refer to this, that person got the same error as you
sry but I'm doing this for the first time. Where do I do this
in the command line
Terminal I think
just paste?
I code in atom so it’s different
Yes
@hasty iron do u know sqlite3
I’m having trouble with an error
if it’s a question about databases it’s better suited for #databases
why is this only happening once?```python
@tasks.loop(seconds=1)
async def checks():
guild = bot.get_guild(861260736457998346)
mute = guild.get_role(883380167865667644)
print(muted)
for member, secsLeft in muted.items():
mem = bot.get_user(member)
if secsLeft == 0:
mem.remove_roles(mute)
del muted[member]
else:
muted[member] -= 1
print('secs left of mute:', secsLeft)
print('starting checks!')
checks.start()```
thx guys
help?
i don't understand
well i was searching from morning
just search "python key error"
@slate swan show me
wht should i define guild with
message
It says key error because it’s not a value in the json file
Ok now try
wht
you can return a default prefix if the guild isn’t inside the json
ohk
so how do i do it
bruh
Dude ur code is fucked
why
First off
something like
prefix = prefixes.get(str(Guild.id))
if not prefix:
# return default prefix
else:
return prefix
Why are u reading it
that was a pain
well i saw it from ytb video
Not that
well actually
alternatively you could just do return prefixes.get(str(message.guild.id), default_prefix)
the different prefixes
It work
it work but it give error also
in discord-ext-menus how do i make the bot remove authors reactions when the author uses it????
one finally question: The bot is now running in my server and works but the bot works only when i push start debugging in the app. I want that the bot runs every time without open programm
now if i want to add code to github so this needs to be changed right????????? help
help @slate swan
help @hasty iron
why tf is it raising this error im using mystbins api
what, if you dont know just dont say anything this is a help channel
help
sorry
soryr
its alright chill
Guys why doesnt my bot make any sound? It has a green circle surrounding it, but it does not play anything.
@client.command()
async def play(ctx, url):
ctx.voice_client.stop()
FFMPEG_OPTIONS = {"before_options": "-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5", "options": "-vn"}
YDL_OPTIONS = {"format": "bestaudio"}
vc = ctx.voice_client
with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
url2 = info["formats"][0]["url"]
source = await discord.FFmepgOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
vc.play(source)
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
same thing happened when i used another module/library too
we cant help
not helping caused against tos
what do other bots use then?
bro its illegal groovy got shutdown dont u know
i know, but then what do, rythm and others use?
same thing afaik. Won't be long before they are also shut
bro its illegal cannot help and ur bot and other bots also will soon receive ciease and desiet case filed against them
soo, that means, i cant use youtube_dl?
no
but u can use spotify though
i can?
help if i want to add bot to github then?? should i change its location
yeah type spotify api in chrome thats it i cannot tell anything else
there's no tutorial telling how to use spotify.......
No, we can't help with it doesn't mean you can't use it. But either way, it breaks ToS, so is it better if you don't use it? Yes. And I'm not telling you to use it.
oh ok thanx
ok, i wont use it
hey tell me
What?
if i want to upload it to github then should i cgnage path
change
You upload the files
then
will it work
Do it, just upload each of your file
ohk it will work right
From file explorer to Github or something
Yes
yes
Can someone send the docs where it's explaining how to get emojis from other servers so the bot can send them?
emoji = bot.get_emoji(878974222163128351)
guild = bot.get_guild(862915601022058526)
w = discord.utils.get(guild.roles, id=862915601022058527)
e = discord.utils.get(guild.roles, id=865269145007816704)
o = ctx.guild.owner
role = [w,e,o]
await emoji.edit(roles=role, reason="Test")
``` i did this. i am the owner of the guild thats why i added `o` but i cant see the emoji without that role whyy???
!d discord.ext.commands.Bot.get_emoji
get_emoji(id)```
Returns an emoji with the given ID.
thanks
help??
I don't understand this code
is there something wrong?
await ctx.send(f"{name1} is best person on the server")
await asyncio.sleep(3)
await ctx.edit(content=f"{name1} is the dumbest person on the server")
Can you explain????
yes
plz tell
it won't work
yes
Hi, I am trying to know if someone is streaming in twitch, by knowing when their activity is in the Streaming category, by now I am trying it using a command, I already have this code inside the command:
guild = bot.get_guild(ID)
member = guild.get_member(ID)
if isinstance(member.activity, discord.Streaming):
print(f"{after.mention} Is streaming")
But this doesn't works, because there are already some people streaming and this doesn't work, where's the problem??
i need help thats why
store the first message in a variable and then use message.edit()
ohhhh
message = await ctx.send(f"{name1} is best person on the server")
await asyncio.sleep(3)
await message.edit(content=f"{name1} is the dumbest person on the server")
``` like this?
Where do I find the emoji ID? @slate swan
Can't find it for some reason when I have developer mode on
yes, should work
k thanx
Enter the emoji into your chat bar, don't press enter, and then put the \ before it
no it did not work
I don't know wym
Anyone know any good alternatives to asyncpraw I'm having some issues with it
help if i want to add it to github
you passed in ID, are you checking for only one member or all members in a guild?
wydm like a request
anyone
yes
its on heroku
how do i connect it on github
@slate swan
I think you can use requests to do it with reddit API
one finally question: The bot is now running in my server and works but the bot works only when i push start debugging in the app. I want that the bot runs every time without open programm
i think u press run without deubbing
debugging
help?
possible
u telling me?
plus json files tend to crash
so they you will loose all your data
so what do I have to do so that the bot runs continuously
I was looking for something like an api wrapper because I've never worked with requests
use asyncpraw
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
I am facing some problems
Asyncpraw is what I'm using rn
I want to check all the members, but for now I am trying it with only one member wich is in streaming
but it doesn't work
There are alot of issues with it
you could make your own
I want to make my own
sql = ("INSERT INTO main(guild_id, prefixes) VALUES(?,?)")
prefix = "!"
val = (guild.id, prefix)
sql = ("INSERT INTO main(loggingstatus,guild_id) VALUES(?,?)")
status = "off"
val = (status,guild.id)
cursor.execute(sql,val)
db.commit()
sql = ("INSERT INTO main(guild_id, invitestatus) VALUES(?,?)")
status2 = "off"
val = (guild.id, status2)
sql = ("INSERT INTO main(verifystatus,guild_id) VALUES(?,?)")
val = (status2,guild.id)
cursor.execute(sql,val)
db.commit()
cursor.close()
db.close()
for some reason this doesn't work and its very confusing lol idk if i have to execute the sql after or some shit
I'm not even close to that level
can u tell other solution with json only cause
json very shit
only for storign temp data
if u want ur stuff to crash then ig go for it
!d discord.ActivityType.streaming try this
A “Streaming” activity type.
and what do i have to do so that the bot runs continuously
or else
let it be
no change prefix lol
or else i will add later
Python driver for MongoDB http://www.mongodb.org
!pypi motor for async version of pymongo
yeah i have heard abt it but i dont know how to work with it in python if u have any video then dm me plis
ill def try this lol
I can help you go through it, it's not hard at all and is very easy to use.
Is bot.get_thread a thing? How do I get a thread? like a channel?
I don't think that's available in the current version of discord.py, and since it's not getting updated anymore you probably should wait for 'disnake.py' to be officially out. It will be out in a few days.
also how do i get the vc id where the author is connected
discord.py 2.0 has thread support
so do u have any recommendations for what i should switch too
!pypi disnake
No, and now returns an error
if isinstance(member.activity, discord.ActivityType.streaming):
Error:
if isinstance(member.activity, discord.ActivityType.streaming):
TypeError: isinstance() arg 2 must be a type or tuple of types
Thanks Error
yes then can we do it a server vc i will live stream and u can help me
"Error", no problem, 35.
i can talk also
wouldnt u pass member instead of discord
and there is also TextChannel.get_thread
Make a help channel.
"Error"
is there any way to return how many threads are in a category or
just a question
It's in version 2.0, is it out?
If whatever you are using returns a list then you can do len(list).
i already have testing bot server
download it via github
no, I think... , because I am checking if the activity is in the discord.ActivityType.streaming category
Invite me to it in DMs.
there is Guild.threads and TextChannel.threads
you could check for TextChannel.category
alr thx
it's pip install repo-link right?
yeah of course
So in this moment the bot only works when i click on run. If i close the program the bot doesn’t work. I want that the bot works when the program is closed and i don‘t know how
thanks
like visual studio?
Yes
Someone?
minimise it
print('duck eaten')
you can't expect the bot to be online after stop running the script
Do you have presence intents enabled?
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="One Piece", status=discord.Status.offline))
```Why is this not working?
the status part aint working
??
not offline
oh ok
yes
is there any way?
with offline you can’t have an activity
but then this will not show the activity
take it out of activity const
take out whichever
!d discord.Client.change_presence
await change_presence(*, activity=None, status=None, afk=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Changes the client’s presence.
Example
```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
if you want to show the activity then don't use offline status
i see
ok sir
Yes, activity and status are separate kwargs
ok and how can i set the bot online?
status = discord.Status.online
Where r u making the bot?
You need to host your bot to keep it online
Visual studio
ok
if you want the bot to run 24/7 then you may use a hosting site
then make the bot and deploy it on heroku
vps
prefer not heroku
@slate swan My bot is still showing online
await client.change_presence(status=discord.Status.offline)
for small bots its ok
well, everyone has their choices
ik
Where are you calling this func?
Do this in your bot constructor instead
umm ok
bot = commands.Bot(..., activity=..., status=...)
ohhhh, i see thanxxxxx
how do i make it so only i the owner can run the command
!d discord.ext.commands.is_owner
discord.ext.commands.is_owner()```
A [`check()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that checks if the person invoking this command is the owner of the bot.
This is powered by [`Bot.is_owner()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.is_owner "discord.ext.commands.Bot.is_owner").
This check raises a special exception, [`NotOwner`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.NotOwner "discord.ext.commands.NotOwner") that is derived from [`CheckFailure`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Nop
, now non of the members is streaming but I'll try and see if now works, thx
how can I have to command names?
like```py
@client.command()
async def disconnect/dis(self, ctx):
pass
make it an aliase
@client.command(aliases=['hi'])
@bot.event
async def on_member_join(member):
db = sqlite3.connect('main.sqlite')
cursor = db.cursor()
cursor.execute(f"SELECT channel_id FROM main WHERE guild_id = {member.guild.id}")
result = cursor.fetchone()
if result is None:
return
else:
cursor.execute(f"SELECT msg FROM main WHERE guild_id = {member.guild.id}")
result1 = cursor.fetchone()
members = len(list(member.guild.members))
mention = member.mention
user = member.name
guild = member.guild
embed = discord.Embed(color=lol,description=str(result1[0]).format(members=members, mention=mention, user=user, guild = guild))
channel = bot.get_channel(int(result[0])
``` full code
``` full code
File "c:\Users\\OneDrive\Desktop\Theft (NEW)\main.py", line 57, in on_member_join
embed = discord.Embed(color=lol,description=str(result1[0]).format(members=members, mention=mention, user=user, guild = guild))
KeyError: 'member'
any ideas ??
add member=member
okay
lol same thing i use
Literally no idea why I keep getting this error. The only things I've not posted are the location of the code within the traceback.
user = self.bot.get_guild(self.config.staff_guild).get_member(x['userid'])
AttributeError: 'NoneType' object has no attribute 'get_member'
self.config.staff_guild is in a json file as "staff_guild": 755251425302544487,
The bot has all intents enabled and is in the guild with the ID specified is the correct ID and the user is in the guild.
guys how can i count the number of bots in a guild
!d discord.Client.guilds len(<--)
guilds```
The guilds that the connected client is a member of.
deleted?
yes
should i rewrite my bot to another discord wrapper cuz discord.py stopped updating ?
i figured it out
he deleted
Nice
ok
@slate swan ?
but pls answer #databases my question
wait
waiting
filter members with member.bot = True
you can do sum([m for m in Guild.members if m.bot])
what will it do?
why member.bot = True
!e ```py
sum(['a', 'b'])
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | TypeError: unsupported operand type(s) for +: 'int' and 'str'
me getting confused
Not sum ig, it'll be len
member.bot returns a bool not a string
member.bot returns True if user a is bot account
so
len(member.bot)
But you have m as items in list
like this?
it can't be summed still..?
Hi, so I have the following code or line
cur.execute(f'''INSERT INTO GUILD_{ctx.guild.id} (user_id) VALUES ({x.id})''')
``` and i need it to ignore if the(user_id) already exists
why are you making a table for each guild
idk i just followed a tutorial
that’s very terrible table design
any other way to find the number of bots
len([m for m in guild.members if m.bot])
^^ makes a new list of members which are bots (or member.bot returns True = which is basically the same thing)
^^ find the length of it
but what is m
a Member object
m is assigned variable to member object
its m for m in guild.members if m.bot
pls answer
Hi I need help. In run docker (20.10.7) with ubuntu 20.04 LTS. I use "python:3.8.12-buster". The problem is the bot can't start for some reason.
ERROR:
iohttp.client_exceptions.ClientConnectorError: Cannot connect to host discord.com:443 ssl:default [Temporary failure in name resolution]
FULL ERROR:
https://ghostbin.com/paste/ePqg0
- Google not helped lol.
I would be very thankful for any help. 😀
Ghostbin is a website where you can store and share text online.
huh
can you do a list of discord.Members inside sum()??
oops
already someone said it
i saw something like that in a tag
len(Guild.members)
including bots ^^
kk thanks
from an rdanny tag
Count your bot's members:
all members: sum([g.member_count for g in bot.guilds])
Human only: sum([m for m in bot.get_all_members() if not m.bot])
bots only: sum([m for m in bot.get_all_members() if m.bot])
Only one guild: ?rtfm guild.member_count
that's wrong isn't it?
https://github.com/Rapptz/discord.py/issues/5960
Maybe this'll help
no clue
!d sum
sum(iterable, /, start=0)```
Sums *start* and the items of an *iterable* from left to right and returns the total. The *iterable*’s items are normally numbers, and the start value is not allowed to be a string.
For some use cases, there are good alternatives to [`sum()`](https://docs.python.org/3.10/library/functions.html#sum "sum"). The preferred, fast way to concatenate a sequence of strings is by calling `''.join(sequence)`. To add floating point values with extended precision, see [`math.fsum()`](https://docs.python.org/3.10/library/math.html#math.fsum "math.fsum"). To concatenate a series of iterables, consider using [`itertools.chain()`](https://docs.python.org/3.10/library/itertools.html#itertools.chain "itertools.chain").
Changed in version 3.8: The *start* parameter can be specified as a keyword argument.
iterable 
"The iterable’s items are normally numbers, and the start value is not allowed to be a string."
normally doesn’t mean always
!e sum([1, 'a', 3])
acc to this ^ it means any other item except first can be string
!d discord.Guild.create_voice_channel
await create_voice_channel(name, *, overwrites=None, category=None, reason=None, **options)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
This is similar to [`create_text_channel()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild.create_text_channel "discord.Guild.create_text_channel") except makes a [`VoiceChannel`](https://discordpy.readthedocs.io/en/stable/api.html#discord.VoiceChannel "discord.VoiceChannel") instead, in addition to having the following new parameters.
thanks
alternatively you couldve just looked it up in the docs
@hasty iron
is it correct
overrides = {ctx.guild.default_role: discord.PermissionOverwrite(speak = False)}
guys
i need help
cur.execute(f'''INSERT INTO GUILD_{ctx.guild.id} (user_id) VALUES ({x.id})''')
``` and i need it to ignore if the(user_id) already exists
i use a list of ids and just check if members id is in the list
and how?
sql injection
how
@kindred epoch plz help
why are you going around pinging people
Do not:
cursor.execute("SELECT * FROM table_name WHERE value = {}".format('peepeepoopoo'))
Do:
cursor.execute("SELECT * FROM table_name WHERE value = ?", ('peepeepoopoo',))
Consider: if a command accepts user input, and they input True; DROP TABLE table_name- The resultant query with format is:
SELECT * FROM table_name WHERE value = True; DROP TABLE table_name which has obvious results.
Utilizing your SQL library's sanitization methods prepares the statement and exclusively inserts the values, without editing the query.
Note postgresql uses $1, $2, ... for value substitution, mysql, %s, so make sure you know your DB!
https://xkcd.com/327
sry
and idk that
ok
and WHERE value = {user.id}?
@kindred epoch
so cursor.execute("SELECT * FROM table_name WHERE value = {user.id}")
?
Ping?
i forgot to reply so i ping
me
not you tho
about this
I mean someone pinged me and deleted
ok
Oh okay
Try it and see
no idea then
ah i see
how can i make bot go offline for certain amount of time?
for example when currenttime == 12:00:
bot(status=discord.Status.offline
or idk
can i use time.sleep to make it go offline?
maybe have a look at the datetime module
@kindred epoch ^^ is that right?
def open_bank_account(userid):
config = get_individual_config()
if str(userid) in config["bank"]:
return False
else:
config["bank"][str(userid)] = int(0)
with open("Individual.json", "w") as f:
json.dump(config, f)```
```py
def get_purse(userid):
indivconfig = get_individual_config()
open_bank_account(userid)
return indivconfig["bank"][str(userid)]```
why is this not working the first time a user not in the file is triggering the get_purse() thing (ping me if you know)
i put checks in them and after stops writing
wait a second i have proven myself to be dumb again
yo what am i tripping
how do you set intents for discord.Client
im having a stroke
class Integrate(commands.Bot):
def __init__(self):
super().__init__(
command_prefix = 'eee',
intents = discord.Intents.all()
)
<Intents value=32767>
but print([k for k in self.bot.guilds]) prints nothing
just []
but
on_message works
Where are you printing that?
If you're printing it before the bot is ready and connected to the gateway, it might not have loaded it's list of guilds yet
OH SHIT ITS NOT AFTER ONREADY
i knew i was having a stroke
my bad
yeah it works
fuck me
thanks
i was almost texting something dumb again
but i relearned how to read errors
-r
lol wrong server
today i am just lost
-r
again
why am i even programming right now
Im doing a blackjack command (with buttons), and i made the buttons. but i they dont really work. im doing:
if inter.clicked_button.label=="hit":
can you say the error
there is none..
:|
am i doing something wrong?
row = ActionRow(
Button(
style=ButtonStyle.red,
label="Hit",
custom_id="hit"
),
Button(
style=ButtonStyle.red,
label="Stand",
custom_id="stand"
)
)
#bla bla bla
rand1=random.randint(1,11)
rand2=random.randint(1,11)
randb1=random.randint(1,11)
randb2=random.randint(1,11)
total=rand1+rand2
em=discord.Embed(title="Black Jack")
em.add_field(name="You", value=f"`{rand1}` `{rand2}` (Total={total})")
em.add_field(name="Dealer", value="`?` `?`")
msg=await interaction.reply(embed=em, components=[row])
# This is the check for button_click waiter
def check(inter):
return inter.author == interaction.author
inter = await msg.wait_for_button_click(check=check)
if inter.clicked_button.label=="hit":
also
its a slash command
your buttons should be in a list pretty sure
wdym tho
no he's done the components part fine
after
inter = await msg.wait_for_button_click(check=check) write print(1)
to see if it triggers
write a bunch of print's to see where it stops printing
it should be easy to figure it out if you print it all, to see the bigger picture
hm, didnt work for me
well
i havent used buttons in a while but from what i can tell it looks fine, its a tuple and tuples work
i got 1 after inter
okay thats a good sign
now print inter.clicked_button.label after inter = await msg.wait_for_button_click(check=check)
so it printed hit?
okay print(1) inside the check (if inter.clicked_button.label=="hit":) to see if it trigger
s
What's the issue with this?
symbols = "à", "á", "â", "ä", "æ", "ã", "å", "ā"
letters = string.ascii_letters
with open("test.txt") as file:
test2 = file.read().split('\n')
@bot.listen("on_message")
async def on_message(message):
guild = message.guild
bypassedRole = discord.utils.get(guild.roles, name="Bypassed")
if bypassedRole in message.author.roles:
return
for word in test2:
regex_match_true = re.compile(fr"[{symbols}]*".join(list(word)), re.IGNORECASE)
regex_match_none = re.compile(fr"([{letters}]+{word})|({word}[{letters}]+)", re.IGNORECASE)
if regex_match_true.search(message.content) and regex_match_none.search(message.content) is None:
await message.delete()
embed = discord.Embed(title="Message Deleted", color=0xD708CC, description= f"{message.author.mention}, You're not allowed to say that.")
embed.timestamp = datetime.utcnow()
await message.channel.send(embed=embed)```
I have no errors, it's not blocking anything with the symbols which is the issue
Like when I'm trying to say àss it's not blocking it
And I don't have any error handlers
Anyone know the issue?
you spelt it wrong
@manic wing didnt work
Should say please pass in all required args
MissingRequiredArgument
Awehhhhh
it didnt print 1?
okay, before the if statement print type(inter.clicked_button.label)
if its not str we know the issue 😎
so print(type(inter.clicked_button.label))
yes
before?
before the if statement
I'm guessing no one knows what's wrong
i can probably figure it out but im too tired, #❓|how-to-get-help
it said
Okay
<class 'str'>
yes
also you haven’t said what you expected it to do
i have
how are you so sure the if statement isn’t triggering
it could something inside the if statement that caused it to break
ok
could be*
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.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.
did you print(1) the first line after the if statement?
is the reply working
which one
nope
and the 1 before it is printing?
none of them are working
you said it printed hit...
.
its ok
is it possible to see all the dms your bot has received
is there a way to send a discord embed with raw http requests
Clearly, @novel apex exists so lol
no, that just does
@bot.event
async def on_message(message):
if isinstance(message, discord.DMChannel):
#do shit```
dont act like a smart ass and reread my question
It's not that serious
?
what?
i called you a tart
its english slang
and then i edited it
once again, dont act like a smart ass
Also it wasn't being a smart ass it was answering your question...
"is it possible to see all the dms your bot has received"
So I said yes, it is possible considering mod mail exists
except you werent answering my question in the slightest, i said all dms your bot has recieved, keyword all. Read slowly
all
not on_message, all
I see
You mean if you wanted to view every message it received in total rather every time it gets DMed send a notification, yes?
yes
Like if you just did a command it would send a txt or something of all the messages
every message thats ever been sent to my bot
I see
i can easily do ```py
@bot.event
async def on_message(message):
if message.channel is None:
list.append(message.content)
but this isnt what im looking for
@client.command()
async def history(ctx, member: discord.Member):
counter = 0
async for message in ctx.channel.history(limit = 100):
if message.author == member:
counter += 1
await ctx.send(f'{member.mention} has sent **{counter}** messages in this channel.')```
This code is how to see the history of messages in a server, however you may be able to use the syntax to re-code it into a thing for the bot
yes but then my bot would need to iter through 70k users to look for messages and i dont feel like inflicting that kind of pain onto my host
you will most probably get rate limited
That wouldn't affect the host of your bot, it'd be the discord api that does that
hence the i dont feel like inflicting that kind of pain onto my host
it would affect both
why didn't you set a log channel for that in the first place
They don't want to get a thing every time it's sent, they want a thing to just get all the messages at a time
which would more than likely be non-doable without being ratelimited
because when i made my bot 5 months ago i didnt think that in 5 months i would need to see it
but there might be another method, hence why i am asking here but apparently you guys are all out of ideas ¯_(ツ)_/¯
I'm not sure but i heard you can log into your bot account
You usually need some form of tool, I don't believe you can just plainly login
thats against tos if it uses an external app
It may work without needing a diff app
im making an app for it, which isnt against the rules because I won't be distributing it
However, I don't do it nor do I look into it so
Didn't you just say if you use an external app it's against tos
yes they asks for your bot's token :kek:
I am making the app
But you're still using it..?
conflicting
it is if you downloaded an external app that has been officially published i believe
Trolling
You can join servers I believe, but you can't do anything as the bot
because it is an interesting project to code
you get a ton of tags and shit
because it's technically a real account but also not lol
no you can't join servers using the bot account
I think a long time ago I did
Maybe it only works with servers it's in
Maybe not, I don't remember nor do I care lmao
if this shit is real then dm spammer bots would take over discord
Has discord.py been archived? What happened? 🥲
read the latest pin
Thanks
Basically that just means no security updates, anything discord adds for bots will not be added, etc, however you can fork the repo still, and contribute on your own time
so if you wanna use slash commands you could very well find a way to have that work with discord.py but, I don't know if it's been figured out yet
I haven't read it yet, but he posted a "a little big" announce.
https://gist.github.com/Rapptz/4a2f62751b9600a31a0d3c78100287f1
what does discord even have let to add?
they added buttons, slash commands, menus.
I cant think of another thing to add
that’s why bots exist
how would they add it tho
if the user join count spikes up by 1000 in under 30 seconds it's probably safe to say the server may be getting raided and it could warn the owner somehow?
Or have some like, lockdown
where it makes 2 step verification be required or a phone number
just make it?
yeah
I'm not good with discord.py 🥲
you can do it manually?
you can
i know
Besides, maybe a user just doesn't have a phone number linked yet or doesn't wanna use 2-step, so that's why you could implement the anti-raid option but they don't have to use it
and discord bots fuck up sometimes, or they could be configured incorrectly
so you expect discord to setup an anti raid system for every server there is?
no like
they can have an option for it to be enabled, they don't need to go to every single server and do it
oh wait
Otherwise discord probably wouldn't wanna make updates if they have to go to every single existing server usually using a script but still going to every single server and having the option enabled
Go on...
like the emojis?
verified?
lemme draw a example
alright
Just out of curiosity, why are GCP, AWS, and Azure not as actively recommended as other providers here?
yes
it already exists iirc
idk
For me it means free competition.
You can set a rules channel if your server is a community one
you want to fork dpy?
Most people will anyway, since they don't update it anymore they might try it themselves(?)
¯_(ツ)_/¯
I was curious which way round he meant, where he gets to have more options for dpy or he gets to be apart of said competition
ah
dpy has problems, wait for a library in the next month or use hikari.
what new lib is coming out in the next month?
this may be the next big thing I'm afraid 😢
i want disnake to be most popular
are the syntaxes difficult? or similar?
exactly the same but it will have slash commands
oh
its a direct replica of discord.py 2.0
cool
Yeah, imo disnake is the way to go.
help how do i get my bot to say something
my guy 
await messagable.send
ctx.send(message)?
where messageable is an instance of a channel
ok thank you
oh
awaitis requiredctxwill not always be used
blah blah 
await is technically not required
you what
if the coroutine is not garbage collected it won’t raise a warning
except for the fact that its asynchronous and await is needed
and you can run that coroutine by doing coroutine.send(None) although it raise StopIteration
and technically we are all pointless critters who have 0 meaning
^
blanket is cooooooool
!e ```py
async def foo(): return 123
coro = foo()
coro.send(None)
@hasty iron :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 4, in <module>
003 | StopIteration: 123
im just saying that it’s technically not required
and technically we're all not nerds
okay?
perfectly valid, just as me saying technically we are pointless
idk I wanted to join lol
Api wrapper
But prepared for bots from trillions of guilds
you said what new lib and they said api wrapper
true
are there really that many guilds? Dayum
Discord plans to extend much more, Today we use 18 digits for IDs but in the future it will be 20.
or more
then there is like some quintillion servers?
wat




