#discord-bots
1 messages · Page 111 of 1
I think embeds' description is a required argument
Which you don't pass to the constructor
You might have two terminals running your bot file or something like that
aaaa yeah
tysm
how to get animated emoji id?
Do cogs need to be formatted as a class to work as intended?
I avoided this by putting this in my on_message
That'll prevent it from logging any bot messages to begin with
@slate swan And how did you make a message counter ??
u can use guild.emojis iterating through them or u could just right click in discord on google open image in new tab
dpy has an is animated check for emojis
Did you add the command to your bot tree?
how can I make it so that the profile displays how many messages you wrote during the time the bot is on the server ?
I know what needs to be used there before and after
Store messages using on_message event and update the activity using tasks.loop
Just use return. It shouldn't continue any of the on_message if the message comes from a bot
apparently you have a previous command that already used the name "commands"
nah i dont, when i remove the "rules" part everything works fine
when i remove this
I remember we were having an issue with this yesterday
You did have a commands command unless you removed it
nah that was a problem with bot permissions or smt like that but i fixed it
ifixed it using async def _commands(ctx):
yk how i can fix it? @sick birch
Provide more info.
like
when it should respond to !version and send an embed it doesnt
i think i need to add awat smt
await
!paste Could you paste your code here?
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
yes ok
from cgi import test
from email import message
from math import degrees
from multiprocessing.sharedctypes import Value
import site
from unicodedata import name
import discord
import http
from discord.ext import commands
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
@bot.command(name='version')
async def version(context):
myembed = discord.Embed(title="Made by Splunk#1157", description="Nice", color=0x00ff00)
myembed.add_field(name="Site", value="", inline=False)
myembed.add_field(name="Date released", value="october 21th, 2022", inline=True)
myembed.set_footer(text="Made by Splunk#1157")
myembed.set_author(name="Made by Splunk#1157")
await message.channel.send(embed=myembed)
await context.message.channel.send(embed=myembed)
@bot.event
async def on_ready():
test_channel = bot.get_channel(1032312979594682491)
await test_channel.send('Hello')
@bot.event
async def on_disconnect():
test_channel = bot.get_channel(1032312979594682491)
await test_channel.send('Hello')
@bot.event
async def on_message(message):
if message.content == "What day is it?":
test_channel = bot.get_channel(1032312979594682491)
await test_channel.send("The day is the 21th")
if message.content == "Thank you for telling me!":
test_channel = bot.get_channel(1032312979594682491)
await test_channel.send("No Problem AnyTime :)")
myembed = discord.Embed(title="Made by Splunk#1157", description="Nice", color=0x00ff00)
myembed.add_field(name="Site", value="s", inline=False)
myembed.add_field(name="Date released", value="october 21th, 2022", inline=True)
myembed.set_footer(text="Made by Splunk#1157")
myembed.set_author(name="Made by Splunk#1157")
await message.channel.send(embed=myembed)
await bot.process_commands(message)
bot.run('')
there
unindent await bot.process_commands(message)
Hello !
I'm a Raspberry Pi 4 user and I want to create a bot with Python with the help of this video :
https://www.youtube.com/watch?v=i7aYBB3znMI
My first code is that ( it's a simple code because I'm a beginer ) :
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='>')
@bot.command()
async def ping(ctx):
await ctx.send('pong')
bot.run('<MYTOLKEN>')
Thene, when I realized it don't work I try that :
import discord
from discord.ext import commands
intents = discord.Intents.default()
bot = commands.Bot(command_prefix='>', intents=intents)
@bot.command()
async def ping(ctx):
await ctx.send('pong')
bot.run('<MYTOLKEN>')
And in the console it's tell me that :
WARNING discord.ext.commands.bot Privileged message content intent is missing, commands may not work as expected.
INFO discord.client logging in using static token
INFO discord.gateway Shard ID None has connected to Gateway.
Sorry for my bad english.
So if you can help me, thank you !
Discord is a fantastic tool to speak with your community (gamers at first, but now more open to other types). You can use web hooks and bots to interact with a server.
Today, we'll see how to do this on a Raspberry Pi with Python.
How to make a Discord bot on Raspberry Pi?
A bot is seen almost as a normal user on Discord, and it's possible to ...
Guys please...
wdym
!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.
ok
It's in the if, it shouldn't be.
You don't need == True
It's better to use a listener anyways.
can yo ulike change the code pls bc idk what you mean
If already checks if its True
Put that code on the same line as the if's.
!indention
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
No you need to unindent that piece of code.
remove one tab
what does unundent
bot.run('<MYTOLKEN>')
And my Axe!
((couldn't help myself))
in that line
unindent
i did it
Okay now you're good.
Just makes it easier in my head to include the ==True there's plenty of ways to do it I was just sharing how I did it
ohhhh ok
oh ok, just saying
You need some intents for this
still doesnt work
!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 Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, 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.
Provide more info, crash etc current code etc we're blind.
tb or if it even reaches ready event.
like theres no error or anything
Show your on_message please.
its just not sending my embed when i do "!version"
btw make the on_message a listener instead of an event because you overwrite the original event, that's why you need to add the process thing
ok i did get errors
I know you've told us that like 4 times, this isn't relevant information.
ok sorry xd
Could you paste that here using Discord code format?
I think they were asking for the whole code block under on_message lol
oh o
from cgi import test
from email import message
from math import degrees
from multiprocessing.sharedctypes import Value
import site
from unicodedata import name
import discord
import http
from discord.ext import commands
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
@bot.command(name='version')
async def version(context):
myembed = discord.Embed(title="Made by Splunk#1157", description="Nice", color=0x00ff00)
myembed.add_field(name="Site", value="", inline=False)
myembed.add_field(name="Date released", value="october 21th, 2022", inline=True)
myembed.set_footer(text="Made by Splunk#1157")
myembed.set_author(name="Made by Splunk#1157")
await message.channel.send(embed=myembed)
await context.message.channel.send(embed=myembed)
@bot.event
async def on_ready():
test_channel = bot.get_channel(1032312979594682491)
await test_channel.send('Hello')
@bot.event
async def on_disconnect():
test_channel = bot.get_channel(1032312979594682491)
await test_channel.send('Hello')
@bot.event
async def on_message(message):
if message.content == "What day is it?":
test_channel = bot.get_channel(1032312979594682491)
await test_channel.send("The day is the 21th")
if message.content == "Thank you for telling me!":
test_channel = bot.get_channel(1032312979594682491)
await test_channel.send("No Problem AnyTime :)")
myembed = discord.Embed(title="Made by Splunk#1157", description="Nice", color=0x00ff00)
myembed.add_field(name="Site", value="", inline=False)
myembed.add_field(name="Date released", value="october 21th, 2022", inline=True)
myembed.set_footer(text="Made by Splunk#1157")
myembed.set_author(name="Made by Splunk#1157")
await message.channel.send(embed=myembed)
await bot.process_commands(message)
bot.run('')
there @cloud dawn
What's the error you get when trying your command
022-10-21 17:13:33 ERROR discord.ext.commands.bot Ignoring exception in command version
Traceback (most recent call last):
File "R\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 190, in wrapped
ret = await coro(*args, **kwargs)
File "\OneDrive\Skrivbord\Disocrd bots\Discord bot.py", line 22, in version
await message.channel.send(embed=myembed)
AttributeError: module 'email.message' has no attribute 'channel'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File R\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
await ctx.command.invoke(ctx)
File "\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 986, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 199, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module 'email.message' has no attribute 'channel'
there
Use context.channel.send instead of message.channel.send
like the second last line?
Hello everyone im new to python and i wanted to learn to make a bot
this is my error
any help greatly appreciated
.event no () needed. @round lily
wont still work
do you know
why it doesnt work
What's the new error message
Show xode
there is none
Their code is here
like theres is not any error
new error is too big to SS do you want the code
remove the ()
If there's no error message in your command prompt then it's doing what you told it to do
when i say !version it should send an embeded text but it doesnt do it
: pain
did you enabel the privilage in your application?
Did you restart the bot after changing it? Does the bot have permission to read and write in that channel?
It's just context.send()
which line
The line where u have message.channel.send
yea bc when i say "Thank you for telling me!" it respondes with No problem 🙂 and an embeded text
Line 22
like give it admin permission?
if so no
cant you like just copy the code and fix it bc i think that is easier
it has admin when i first invited it
Can u post ur version command code
Copy pasting on mobile is hard
ok wait
from cgi import test
from email import message
from math import degrees
from multiprocessing.sharedctypes import Value
import site
from unicodedata import name
import discord
import http
from discord.ext import commands
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
@bot.command(name='version')
async def version(context):
myembed = discord.Embed(title="Made by Splunk#1157", description="Nice", color=0x00ff00)
myembed.add_field(name="Site", value="", inline=False)
myembed.add_field(name="Date released", value="october 21th, 2022", inline=True)
myembed.set_footer(text="Made by Splunk#1157")
myembed.set_author(name="Made by Splunk#1157")
context.send()
await context.message.channel.send(embed=myembed)
@bot.event
async def on_ready():
test_channel = bot.get_channel(1032312979594682491)
await test_channel.send('Hello')
@bot.event
async def on_disconnect():
test_channel = bot.get_channel(1032312979594682491)
await test_channel.send('Hello')
@bot.event
async def on_message(message):
if message.content == "What day is it?":
test_channel = bot.get_channel(1032312979594682491)
await test_channel.send("The day is the 21th")
if message.content == "Thank you for telling me!":
test_channel = bot.get_channel(1032312979594682491)
await test_channel.send("No Problem AnyTime :)")
myembed = discord.Embed(title="Made by Splunk#1157", description="Nice", color=0x00ff00)
myembed.add_field(name="Site", value="", inline=False)
myembed.add_field(name="Date released", value="october 21th, 2022", inline=True)
myembed.set_footer(text="Made by Splunk#1157")
myembed.set_author(name="Made by Splunk#1157")
await message.channel.send(embed=myembed)
await bot.process_commands(message)
bot.run('')
!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.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Bro, you just pasted it literally
Fill the embed kwarg and await it
He's saying it should be context.send(embed = myembed)
You're not telling it to send anything
but didnt i try that
there we go
And await it↑
where do i put await
Yea await. I have a habit of missing that and fixing after error lol
await context.send(embed=myembed)
oghhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
ok tysm
bruhhhhhhh whatttttt
it still doesnt send my embed text
How are u invoking
invoking?
Using
the code?
Command
i say in my server "!version"
On discord
it should send embed text when i do it
Then u are doing a silly mistake somewhere
bruh whereeeeeeee then
Still no error messages?
from cgi import test
from email import message
from math import degrees
from multiprocessing.sharedctypes import Value
import site
from unicodedata import name
import discord
import http
from discord.ext import commands
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
@bot.command(name='version')
async def version(context):
myembed = discord.Embed(title="Made by Splunk#1157", description="Nice", color=0x00ff00)
myembed.add_field(name="Site", value="", inline=False)
myembed.add_field(name="Date released", value="october 21th, 2022", inline=True)
myembed.set_footer(text="Made by Splunk#1157")
myembed.set_author(name="Made by Splunk#1157")
await context.send(embed = myembed)
await context.message.channel.send(embed=myembed)
@bot.event
async def on_ready():
test_channel = bot.get_channel(1032312979594682491)
await test_channel.send('Hello')
@bot.event
async def on_disconnect():
test_channel = bot.get_channel(1032312979594682491)
await test_channel.send('Hello')
@bot.event
async def on_message(message):
if message.content == "What day is it?":
test_channel = bot.get_channel(1032312979594682491)
await test_channel.send("The day is the 21th")
if message.content == "Thank you for telling me!":
test_channel = bot.get_channel(1032312979594682491)
await test_channel.send("No Problem AnyTime :)")
myembed = discord.Embed(title="Made by Splunk#1157", description="Nice", color=0x00ff00)
myembed.add_field(name="Site", value="", inline=False)
myembed.add_field(name="Date released", value="october 21th, 2022", inline=True)
myembed.set_footer(text="Made by Splunk#1157")
myembed.set_author(name="Made by Splunk#1157")
await message.channel.send(embed=myembed)
await bot.process_commands(message)
bot.run('')
see the code
yes no error msg
• Are intents turned on, on dashboard?
• Is the bot having permissions wherever you're testing?
• Is the code being updated properly?
What error does this give?
yea the bot had admin when i inved it, yea the code is being updated prop
idk what is intents
user = ['1031053618008301588']
for member in user:
await user.send(f"Bot has joined {invite}")
Traceback (most recent call last):
File "/home/runner/funny-bot/venv/lib/python3.8/site-packages/discord/client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "main.py", line 514, in on_guild_join
await user.send(f"Bot has joined {invite}")
AttributeError: 'list' object has no attribute 'send'
but i think so yea
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Try send_message( instead of send( I had to do that with my slash commands
Go to dev. dashboard, and check the toggle (you can find it where you obtain token)
trying to send a message to all users in a list any help?
#discord-bots message certification error is due mac being mac.
im on a mac...what
it is turned on
me?
Yes
oh so im just assed out
oh
which line
It happends on every os lol just follow the message url.
line 22?
The same line you've been editing this whole time. await context.send_message(embed=myembed)
This won't change anything
It's a prefix based cmd
didnt work
Honestly just guessing at this point. I do a lot more with slash commands and I remember running into that for some problem I had a week or two ago
is there a url all these just take me to lines causing errors
oh wait
bruh what should i do
I've provided an url here.
Try just sending a regular message without an embed and see if that works
await context.send("this is a test")
Add this in your code py @bot.listen('on_command_error') async def error_handler(ctx, error): raise error, we can catch error with this probably
ok
which line xd
On a new line, then restart your bot and try again it should spit out an error for you
Use the command on Discord
One sec I'm gonna get on my computer and see if I can replicate the problem on my bot

You've pasted it enough lol
from cgi import test
from email import message
from math import degrees
from multiprocessing.sharedctypes import Value
import site
from unicodedata import name
import discord
import http
from discord.ext import commands
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
@bot.command(name='version')
async def version(context):
myembed = discord.Embed(title="Made by Splunk#1157", description="Nice", color=0x00ff00)
myembed.add_field(name="Site", value="s", inline=False)
myembed.add_field(name="Date released", value="october 21th, 2022", inline=True)
myembed.set_footer(text="Made by Splunk#1157")
myembed.set_author(name="Made by Splunk#1157")
await context.send("this is a test")
await context.message.channel.send(embed=myembed)
@bot.event
async def on_ready():
test_channel = bot.get_channel(1032312979594682491)
await test_channel.send('Hello')
@bot.event
async def on_disconnect():
test_channel = bot.get_channel(1032312979594682491)
await test_channel.send('Hello')
@bot.event
async def on_message(message):
if message.content == "What day is it?":
test_channel = bot.get_channel(1032312979594682491)
await test_channel.send("The day is the 21th")
if message.content == "Thank you for telling me!":
test_channel = bot.get_channel(1032312979594682491)
await test_channel.send("No Problem AnyTime :)")
myembed = discord.Embed(title="Made by Splunk#1157", description="Nice", color=0x00ff00)
myembed.add_field(name="Site", value="", inline=False)
myembed.add_field(name="Date released", value="october 21th, 2022", inline=True)
myembed.set_footer(text="Made by Splunk#1157")
myembed.set_author(name="Made by Splunk#1157")
await message.channel.send(embed=myembed)
await bot.process_commands(message)
bot.run('')
there
You didn't add error handler?
i did but removed it
i cant put custom emoji in embed title
is it possible to do that?
i thought that its not possible to put in embed titles..
discord.ext.commands.errors.CommandNotFound: Command "marcar" is not found```
It's not
whats wrong?
😦
Just Command not found
thanks for your help so far i promise im trying to figure this out i clicked all the permissions in dev portal but this
how do you solve?
do i need to do something with the permission integer
Make a command named marcar
@mighty pilot you done?
"@bot.command(aliases=["streaming"])
async def stream(ctx, *, message):
await ctx.message.delete()
stream = discord.Streaming(
name=message,
url=" had to remove this because of bot",
)
await bot.change_presence(activity=stream)", the activity is still green for the bot
Still messing with it. I'll ping if I figure it out
ok
i may not respond asap
can anyone pls help
!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.
async def stream(ctx, *, message):
await ctx.message.delete()
stream = discord.Streaming(
name=message,
url="",
)
await bot.change_presence(activity=stream)```
yes
Decorators begins with @
@honest shoal can u pls help
When you invited the bot did you specify that you were going to use slash commands?
That's now how u change presence
wait what, how do i change it
@round lily
Wait a min, are u getting any error@blazing star
how can i add two images in the same embed?
2 per 10 minutes i believe
just went back and did it
kicked and added the bot again but same error
@honest shoal can u pls help me fixing it
So 20 times per 10 minutes if you were to host 10 bots on a seperate ip.
stream=discord.ActivityType.Streaming, name=message, url=""
&
activity=discord.Activity(type=stream)
sure if you want to think of it that way
that's still about 1 edit per 30 seconds on aveage
error says to try"disabling privileged intents"
its like when i say .streaming the both streams waht i said yk?
With discords move to slash commands did they stop bot commands entirely?
why is this so hard the guys on yt make it look so easy
because it's really not that easy
the tutorials on youtube are usually wrong
@honest shoal
That's a quite generous way of putting it.
... horrifically garbage?
how can i add two images in the same embed?
bot youre already an admin how many more privileges do you want from me
my bot
just enable the intents it's asking
it's in the dev portal
it should be under the "bot" section
am on my pc now, hold on
@blazing star this will work for youpy await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.streaming, name=message, url=""))
you can't
Pagination is as close as it gets.
We don't help with that, sorry.
its for ids
so when my bot joins a server it will message mods the invite
for certain ids in a list
having a list of member object you could use discord.Member.send
!d discord.Member.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=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/latest/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.10)") of [`File`](https://discordpy.readthedocs.io/en/latest/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/latest/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.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
Honestly I think your best bet is going to be to move that command under the on_message block
wdym by that can you like send the code
Hold on I found something let me try it
actually u can
@slate swanchange your @bot.events to @bot.listen() (and remove that bot.process thing obv)
wait how?
one second. ill show
isn't that only for twitter embeds
nah someones got an example
show pls
ok
URL = 'https://www.google.com/'
IMAGE_1 = 'https://cdn.discordapp.com/embed/avatars/1.png'
IMAGE_2 = 'https://cdn.discordapp.com/embed/avatars/2.png'
# embeds must have the same url
# works with more up to 4(?) embeds on desktop, might not work at all on mobile
embed1 = discord.Embed(
title='TITLE 1',
description='DESCRIPTION 1',
url=URL # <<< same url as other embeds
)
embed1.set_image(url=IMAGE_1)
embed2 = discord.Embed(
title='TITLE 2',
description='DESCRIPTION 2',
url=URL # <<< same url as other embeds
)
embed2.set_image(url=IMAGE_2)
await channel.send(embeds=[embed1, embed2])
@honest shoal
OH
that's a nice hack I believe
@sick birch ok so its at least online now but i assume this is abnormal
is it enabled in your code?
since your command overrides your on_message event you need to tell it to check for commands first. so in the on_message event you need to add await bot.process_commands(message) in the first line under async def on_message(message)
where do i put those
xd
yup
one second ill fix your code and send it here
yes pls
from email import message
from math import degrees
from multiprocessing.sharedctypes import Value
import site
from unicodedata import name
import discord
import http
from discord.ext import commands
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
@bot.command(name='version')
async def version(context):
myembed = discord.Embed(title="Made by Splunk#1157", description="Nice", color=0x00ff00)
myembed.add_field(name="Site", value="", inline=False)
myembed.add_field(name="Date released", value="october 21th, 2022", inline=True)
myembed.set_footer(text="Made by Splunk#1157")
myembed.set_author(name="Made by Splunk#1157")
await context.send(embed = myembed)
@bot.event
async def on_ready():
test_channel = bot.get_channel(1032312979594682491)
await test_channel.send('Hello')
@bot.event
async def on_disconnect():
test_channel = bot.get_channel(1032312979594682491)
await test_channel.send('Hello')
@bot.event
async def on_message(message):
await bot.process_commands(message)
if message.content == "What day is it?":
test_channel = bot.get_channel(1032312979594682491)
await test_channel.send("The day is the 21th")
if message.content == "Thank you for telling me!":
test_channel = bot.get_channel(1032312979594682491)
await test_channel.send("No Problem AnyTime :)")
myembed = discord.Embed(title="Made by Splunk#1157", description="Nice", color=0x00ff00)
myembed.add_field(name="Site", value="", inline=False)
myembed.add_field(name="Date released", value="october 21th, 2022", inline=True)
myembed.set_footer(text="Made by Splunk#1157")
myembed.set_author(name="Made by Splunk#1157")
await message.channel.send(embed=myembed)
bot.run('')```
try that
does commands.Bot() not do this already tho???
i guess not? i just did a bit of testing with my bot and unless i specified that line in on_message it wouldnt register that i was using a command
this didnt work
bu ti have fixed it
what was your fix
please refrain from spoonfeeding
2022-10-21 18:36:31 ERROR discord.ext.commands.bot Ignoring exception in command version
Traceback (most recent call last):
File "C:\Users\getbe.R\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 190, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\getbe.
await context.send(embed = myembed)
File "C:\Users\getbe.e 841, in send
return await super().send(
File "C:\Users\OR\AppData\Roaming\Python\Python310\site-packages\discord\abc.py", line 1536, in send
data = await state.http.send_message(channel.id, params=params)
File "C:\Users\g\AppData\Roaming\Python\Python310\site-packages\discord\http.py", line 744, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.fields.0.value: This field is required
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\R\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 986, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 199, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.fields.0.value: This field is required
that was ur error
Overriding the default provided
on_messageforbids any extra commands from running. To fix this, add abot.process_commands(message)line at the end of youron_message
idk i just added ur thing
and it worked
BRUHHHHHHHHHHHHHHHHHHHHHH
noted, just been trying to figure this out for a while now so i thought itd be easier to just copy paste as opposed to trying to explain
now it doesnt send the respond to thank you for telling me or what day is it and when i turn the bot online it doesnt just automaticly say hello
like it should
where did you put it
under async def on_message(message):
move it below your if statements
makes sense
so under that
Below both of those blocks, so it executes the if statements before looking for commands
can you take an ss
if i take a screenshot itd be of my code and it would be very out of context for you, im not on computer anymore
ok of the code you edited or sended
i am dizzy what do i put under what
Put it on line 53 instead of 37
Below that
Read this link
me?
my commands should be here correct
Yes
kk
is there anything wrong here im not getting errors but i cant interact w/ bot
Which library
nextcord
Can't help with that 
whats something you can do because clearly this isnt working for me
Is command not getting registered?
I hope you have enabled application.commands scope while inviting the bot
i did im trying so hard
this so much more complicated than java
brain literally not big enough
Try asking here, if u need help quick
thx
i have a button menu that pops up for members to select a role after sending so many messages, is there a way to check for interaction.user to be the same user that sent the message which triggered the view?
nvm i have something to try first
good library 
disnake >>
understandable
that said, disnake's soon-to-be new docs are 
api reference has been broken into smaller parts that dont take 15 seconds to load in browser
ok so i have the original interaction already specified in __init__ for my view, can i pass that to the buttons inside the view?
hi
i figured out my issue and it pissed me off immensely
so i will remove the things ok
tysm for the help i will try to start from the beginning
apparently i have to also enable bot permission in my server settings even if i already did it in dev portal
:annoyed
yea thats an important step and why i asked if your bot had permissions in your server
it had me give permissions in the dev portal i though it carried over if it doesnt why even put that step there
Are they using mkdocs?
role permissions are important too
whatever it works so thanks for the help 10/10 people all of you
also i wasnt reading names and thought you were splunk when i sent this lol my b
banana
sphinx
yo anyone here i need help
bot = commands.Bot(command_prefix="!", case_insensitive=True, help_command=None)
^^^
SyntaxError: invalid syntax
what did i do wrong here?
@mighty pilot
do you know?
this should work fine, send your code, error messages may be inaccurate sometimes
Anyone have any idea why my bot won't ping roles even though it has the perm to do so?
It's mentioning them but not pinging? Is it in an embed?
make sure the role is mentionable as well as what zeffo said
how can i create a channel with a 'everyone read_messages' false ? and another role has a 'read_messages' true
You do that in discord channel settings. You can set channel read messages for everyone to false and for a role to true
No, an actual message
The bot can mention all roles
I should mention that it is a slash command
@app_commands.command(name="docket", description="Has the bot announce the next item on the city council docket.")
@app_commands.guild_only()
@app_commands.checks.has_any_role(646549322682466305, 646551227626160139, 673008336010084378)
@app_commands.describe(first="True of False: This is the first item on the docket for the session.", docket_item = "The name of the item on the docket.", docket_link = "The Trello link to the item on the docket.")
async def docket(self, interaction:discord.Interaction, first:Literal["True", "False"], docket_item:str, docket_link:str):
if interaction.channel.name.startswith("council-session"):
if first == "True":
await interaction.response.send_message(f"The first item on the docket is *\"{docket_item.title()}\"*. \n\n{docket_link} \n\n Floor is open for debate. Say \"I\" to be recognized. (<@&646549329493884929>)")
else:
await interaction.response.send_message(f"The next item on the docket is *\"{docket_item.title()}\"*. \n\n{docket_link} \n\n Floor is open for debate. Say \"I\" to be recognized. (<@&646549329493884929>)")
else:
raise commands.UserInputError("The docket can only be announced in a session channel.")
pass
pass
@slate swan
Nope, only displays the role
only thing that would be causing it not to mention is permissions
Sometimes when I start up my bot, I get this error, and Im not sure what is causing it. It doesn't happen every time I start my bot. I think it happens when my bot is in the middle of starting up and someone sends a message in the server? Im not sure.
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\kouxi\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 502, in _run_event
await coro(*args, **kwargs)
File "c:\Users\kouxi\Runa\cogs\leveling.py", line 27, in on_message
async with self.bot.db.cursor() as cursor:
AttributeError: 'Bot' object has no attribute 'db'
This is the error
#add xp on message and checking for leveling up
@commands.Cog.listener()
async def on_message(self, message):
if message.author.bot or message.guild is None:
return
author=message.author
guild=message.guild
async with self.bot.db.cursor() as cursor:
await cursor.execute('SELECT levelsys FROM levelSettings WHERE guild = ?',(guild.id,))
levelsys=await cursor.fetchone()
if levelsys and not levelsys[0]:
return
await cursor.execute('SELECT xp FROM levels WHERE user = ? AND guild = ?',(author.id,guild.id))
xp=await cursor.fetchone()
await cursor.execute('SELECT level FROM levels WHERE user = ? AND guild = ?',(author.id,guild.id))
level=await cursor.fetchone()
if not xp or not level:
await cursor.execute('INSERT INTO levels (level, xp, user, guild) VALUES (?,?,?,?)',(0,0, author.id, guild.id))
try:
xp=xp[0]
level=level[0]
except TypeError:
xp=0
level=0
if level < 5:
xp+=random.randint(1,3)
await cursor.execute('UPDATE levels SET xp = ? WHERE user = ? AND guild = ?',(xp,author.id,guild.id))
else:
rand=random.randint(1,(level//4))
if rand==1:
xp+=random.randint(1,3)
await cursor.execute('UPDATE levels SET xp = ? WHERE user = ? AND guild = ?',(xp,author.id,guild.id))
if xp >= 100:
level +=1
await cursor.execute("UPDATE levels SET level = ? WHERE user = ? AND guild = ?",(level,author.id,guild.id))
await cursor.execute("UPDATE levels SET xp = ? WHERE user = ? AND guild = ?",(0,author.id,guild.id))
await message.channel.send(f'{author.name} has leveled up to level {level}!')
await self.bot.db.commit()
This is the block of code, in my Cogs under leveling.py. I have bot.db=await aiosqlite.connect('level.db') in my main.py file under on_ready().
Thank you!
id recommend connecting to your db in setup_hook instead of on_ready
@vocal snow @slate swan
is the role mentionable though
Yes
that toggle is on?
this dont matter. bot has admin
use await Bot.wait_until_ready() before loading that cog
can someone help me with a problem in my view for a button menu? i have interaction_check working properly, but i want to send a message when it returns False but cant figure it out. theres no errors happening so i cant use on_error
can you show me how to use setup_hook? ive never done that before
also what is the difference between using on_ready and setup_hook?
setuphook is only called once while on ready is not
Can someone exlain how I can use the class discord.AllowedMentions on a message for it not to ping @ everyone if it has the perms to do it. I have no clue how I would should use it
can someone show me how to pull up SQLite so i can view my database tables? ive seen videos where its supposed to be on this tab but i dont know how to get it there
You can use:
is there no built-in version for VSC?
Not sure, maybe look for an extension
QQ: can you edit an ephemeral message, does it have to be a response?
Do you have admin in the server? Are you sure you can see the channel?
did you sync?
I already detected the error
missing a @ before the commands.slash_command
I have a question. Watching tutorial on YT, it's so often to see people use ctx. They call it context. But what does that actually mean? Does that mean the same thing as self?
ctx refers to the commands.Context object that is typically passed around in commands, checks, converters, etc.
Yeah, I've read the docs. It pretty much says that, but conceptually, I don't really get it
That definition feels too high class for me to understand. Do you think you can give me something like an analogy?
its separate from self because self is often the instance of the class that methods are defined within, although the purpose is similar
the actual word context means information that is needed to fully understand something
so in this case, that Context object provides you various attributes like the message that triggered the command (.message), the Command object that was invoked (.command), the specific name used to invoke that command (.invoked_with), etc.
ctx.message returns the message object?
yes, if you wanted to
Now, I see ctx.send() and the function is self explanatory. But I just don't understand why do we need to have this when we have await send blablabl
Because I know sometimes we use the latter
several of the context's properties/methods are just shortcuts for common things developers use
why write ctx.send() when you can write message.channel.send()? because its more convenient
If they're just shortcuts, there should be absolutely zero frowns if one wants to use the longer one for, say, consistency?
the two methods work equivalently but you might get frowned upon for not taking advantage of the "simpler" method
I see
So in conclusion, just to make sure I understand this properly:
ctx basically says SOMETHING that triggers this command (only a method decorated by @client.command() will have ctx). ctx.author means return the author (<name>#<identifier>) of the user that just invoked this command. ctx.message means return the message object that was sent by a user that caused this command to be invoked.
That being said, not all methods available are for checking what triggered this command. For example, ctx.send() is a method that serves as a shortcut to do quick reply back.
you could think of the context as being provided in the event that someone uses a command
an on_message event is triggered when someone sends a message and you're given a Message object with information about that message
and in the event someone invokes a command, you're given a Context object with information about the invocation of that command
Hello everything is fine? can anyone help me on how to handle an api via python to send the response via webhook?
You also have two kinds of context with discord.py. Valid & In-valid context, in the case of context being given via command invocation you have a valid context object since it has a command, args, etc to it's name. Whilst you can still get a context object from using a message object alone (await Bot.get_context(message)) It won't always be valid, e.g no command to it's name, no args, etc.
Using non async code could make my bot get ratelimited?
Message: 'Shard ID %s heartbeat blocked for more than %s seconds
Found this on the traceback
that doesnt mean being ratelimited, but that your bot was prevented from sending a heartbeat to discord to keep its websocket connection alive
but non async (or more accurately, blocking) code would cause that to occur
technically argument parsing would come later, get_context only gathers the prefix and command to determine the "validity" of the context
forgot to send but there's also a ton of messages telling me that im getting ratelimited
[2022-10-21 08:13:37] [INFO ] discord.gateway: Shard ID None has connected to Gateway (Session ID: 82f5d315e4cdf95e9424f225e719837c).
[2022-10-21 08:13:37] [WARNING ] discord.gateway: WebSocket in shard ID None is ratelimited, waiting 59.31 seconds
[2022-10-21 08:14:37] [WARNING ] discord.gateway: WebSocket in shard ID None is ratelimited, waiting 0.01 seconds
Also this
[2022-10-21 08:30:30] [WARNING ] discord.state: Shard ID 0 timed out waiting for chunks for guild_id guild_id_here.
[2022-10-21 10:22:26] [INFO ] discord.gateway: Shard ID None has successfully RESUMED session session_id_here.
anytime i run my python code, i get a error saying
Any idea what causes this? Is it the roles i have assigned not allowing the script to perform its task
Error mentions why, seems to be a warning tho.
Hello! I want to actively check if a variable is 1 or not and then send a message in the chat but it doesnt work quite right
(I'm using replit temporarily dont worry :)! )
😄
Seems like the bot has a problem getting the channel
Is the channel ID correct?
yes
maybe try fetch_channel? that afaik may happen if the channel hasn't been cached (or stored) yet
yup
why it may not be cached is likely due to the fact you're running the code in a task? (although I'm not sure)
I don't know if thats related 🤔
made it fetch_channel now this came
you need to await fetch_channel
didn't see that 🤦♂️
you can remove the fetch_channel entirely if you wait_until_ready in the tasks before loop
@tasks.loop()
async def task():
...
@task.before_loop
async def wait_until_ready():
await bot.wait_until_ready()
yup thanks guys
it's commands.Bot with a capital B
Perfect ty, how can i declare a prefix though now?
it tells you in the terminal what the kwarg is called
and where it wants it placed
Thank you, i got it working now
Is there some kind of a example with: slash commands, tasks, commands in a pretty class?
I have tons of examples but combined it's a bit of a pain.
AttributeError: 'Bot' object has no attribute 'commmand'. Did you mean: 'command'?``` whats arrong?
AttributeError: 'Bot' object has no attribute 'commmand'. Did you mean: 'command'?
Did you?
triple m in command?
Are you using discord.py?
Yes
https://github.com/Rapptz/discord.py/tree/master/examples/app_commands unfortunately not many
Just need a starting point. Thx
what does ur bot do ?
What does an unknown interaction error indicate?
You're probably trying to respond to the interaction too late. Make sure you're deferring before doing anything else.
whatcha doin with paypal though?
Understood, thank you
Im trying to get it to read a users paypal history to give them a role based on their recent transaction
From a github repo
i tried this
attachments = message.attachements
temp = []
for attachment in attachments:
temp.append(attachment.url)
print(''.join(temp))
can someone tell me where i went wrong?
@full lily hey, would you know anything about this?
ok so i dont understand fundamentals of bots is there anything good to teach me what goes into making a bot
saves bans into a database
has some events
although I didn't use async for the db
idk if its related
im working on it tho
this would more than likely be it. u using sqlite?
mongodb
oh. yea i would say thats whats blocking the heartbeats. I had a similiar issue
is there any good tutorial for using async with mongodb?
thanks
yup
Not sure what you mean by what goes into making a bot, but here are some resources
https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html the command framework
Make sure you're familiar with python before attempting to use discord.py
perhaps they mean the actual API provided by discord, though you dont need to know too much about it before using an API wrapper
you only have to know guilds are servers /j
thanks a ton
Hi hello all, I have a question maybe it's easy but I haven't been able to figure it out.
I want bot to look for occurrences of a substring in a string then responses, so I used "substring" in "string", it worked, but I want look for more substring, so I made a list or [ ] and ( ) containing the substrings to look for , but when I look for more than 1 substring it doesn't work, when I running not come out any error idk why ?
Is it that does not work look for more than 1 or needs to use other codes?
This is what I tried
So you want the message to contain any word in a list?
Because "('A', 'B')" won't be in the message, neither will a tuple
You need to loop through your list of words and check if each is in the message
For instance:
words = ["apple", "banana", "orange"]
The if statement would only work if the user's message contains one of those words?
You can do this with a for loop,
Or a more advanced (but shorter and cleaner) list comprehension, and the any() function
yes, I want bot look for 1more than word.
this also feels like basic python that you should know before discord.py
Are you just gonna ignore my answer lol
no
Then yeah:
@bot.listen()
async def on_message(message: discord.Message) -> None:
words = ["apple", "banana", "orange"]
if [word for word in words if word in message.content]:
# do something...
let's not be patronizing please
hold on i think this is wrong
At least be correct if you're gonna spoonfeed
No spoonfeeding. Giving them a general skeletal structure, like I always do 🙂
They'll still have to take the concept and figure out how to incorporate it into their own code
Your list comp order is wrong, bool(list) is always true if it isn't empty
.. Yeah ok buddy
Yes, that's what I'm using
The list is empty if a word in words was not found
The list can contain the words that appeared in the message.content, if they want to store that and use it for anything else
But if they're just checking if it's empty/not, a list comp without being assigned a variable will do
actually alright that works
@bot.listen()
async def on_message(message: discord.Message) -> None:
words = ["apple", "banana", "orange"]
present_words = [word for word in words if word in message.content]
if present_words
print("These words were present in your message:", ", ".join(present_words)) # or ctx.send, you get the idea
confused with print statement :p
either way i don't think this is their usecase
it's there if you need it
that literally is spoonfeeding though- you've given the whole code that they need
How is that a 'general skeletal structure'
Copy pasting it isn't going to work
How so?
More than likely they don't have typehints or a listener rather than an event
So they'd need to adapt it to their own
If I'm just looking for string
Spoonfeeding would be if I copied this: <#discord-bots message>
Fixed it for them, and they could copy and paste and move on with their day
a list like this will work
Just put if p_message in list >> if list in p_message . it will be useless
what is p_message?
but that's exactly what you've done, with extra
They can just copy the list comp and if statement
spoonfeeding would imply that you could just copy paste it into your code and it would work, but even the substrings are just examples that the OP wouldnt want;
if the OP were to correct the code to serve their desired purpose, that would demonstrate at least a basic understanding of how the code works
Sure. That's the important bits. They'd still need to figure out where to put it, incorporate it with any other logic going on, adapt variable names to existing variable names, and of course change apple banana orange
Copy pasting this really wouldn't do what they want. The if statement body is commented out, so syntax error as well
though for your example i would consider using any() + generator rather than a list comp, just so it finishes early when a keyword is found
So doing 95% of it for them isn't spoonfeeding?
True, we would have to create our own generator or is there something built in I'm not aware of?
nah just a generator expression is good enough
I must admit I haven't gotten around to those yet :p
any(w in s for w in seq)
didn't know that was a generator 🤔
I was under the impression it created a list and spread it using * internally
the explicit syntax would look like any((w in s for w in seq)), with the extra parentheses turning into a genexpr object
thanks a lot suggestions I will try again m(_ _)m
nah, for that you have to pass to the tuple constructor
just because they have to find where to paste it, and change up placeholders doesn't mean it's not spoonfeeding
The whole term spoonfeeding is subjective in a sense of level of what you consider it being "spoonfeeding", i would say starting a discussion about it would be a waste of time, but be my guest
i dont think its 95% of the work because while it shows a technique for finding one of multiple substrings, robin fabricated a basis to demonstrate the technique (listener, message variable, 3 fruits, missing block after if), which is nowhere close to the original snippet
Yup. The point is to take away the important concepts, I don't even intend for them to copy and paste it. I would prefer they don't, and use it as a structure. I can't force what they do, and I don't want to make things confusing to force them either. If they want to copy and paste and fill in the placeholders - that's fine. That's their call to make. If they want to take away the concepts - that's fine too.
and why not just give pseudocode/similar explaining how to do this?
I doubt they understand what that list comp or later suggested generator is even doing
That's on them to to research or ask questions if they don't understand
It's their job to take responsibility for their own learning. We just provide the necessary resources and help
I've done what I judged is to be the best course to provide assistance, now it's up to them to take that where they will
why not explain it and teach them instead of giving answers and leaving it up to them to figure it out
I don't believe in that level of hand holding. If they're confused, I would be more than happy to explain and help out. This isn't middle school. The resources are all here - it's up to them to utilize it however they wish
sorry Im silly, asked a stupid question like I just said it could be as easy as
I also tried googel to find what I wanted to know before asking a question here or try to read some official api and something..., but Ive been stuck here for 1~2days, maybe I should learn it all over again
what
Can someone help with discord.py?
I just want to know what's causing this error TypeError: 'Guild' object is not iterable
py role = discord.utils.get(ctx.guild, name='Muted') await user.remove_roles(user, role)
i think youre looking for ctx.guild.roles
ctx.guild is a Guild object
guild.roles is a list of Role objects
also, remove_roles doesnt take user, just the roles to remove
Thank you!!
I'm not sure why I did the instruction correctly but my bot don't online on my private server:
import discord
from discord.ext.commands.core import commands
from discord import permissions
bot = commands.Bot(commands_prefix='.')
#run bot
bot.run("")```
It’s probably because from discord.ext.commands.core import commands try changing it to from discord.ext import commands
okay mate
did and it brought me this:
Small typo, command_prefix= not commands_prefix=
You have command__s___prefix instead of command_prefix
👍
so i have to retype from discord.ext import command too?
or i can stay commands
commands
i see
Not there, I mean inside of the commands.Bot(...)
now it says command is not defined
from discord.ext import commands for the import and remember it’s command_prefix=
oh sorry my bad read
async def talker():
get_channel_id = hariku_client.get_channel(ctx.channel_id)```
```py
ctx isnt defined```
commands.Bot()
i rerun and it showed this
from discord import Intents
bot = commands.Bot(command_prefix=".", help_command=None, intents=Intents.all())```
dont put help_command=None before atleast making ur custom impl
also to be explicit its better to use discord.Intents.all() but totally up to u
yeah, i do that alot tho
the program said back
intents parameter must be Intent not <class 'method'>
can u show me how can I use this?
async def talker():
get_channel_id = hariku_client.get_channel(ctx.channel_id)```
```py
ctx isnt defined```
how do i fix this?
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all()) # u have to enable all intents in dev portal as well
@bot.event
async def on_ready():
print(f"Logged in as {bot.user}")
bot.run('YOUR_TOKEN')
ohhhh
ctx is not declared in the function scope
so that's how it work
pass it as a parameter
i thought u say this must be define first
it sent me this
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
it just literally said what u have to do
can someone help me add and load cogs in 2.0, and respond to this message with pings so i can see it
damn finally my bot online tysm!!!!
alright, i did that, theres one small error again lol!
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'send'
Code:
await get_channel_id.send(message)```
get_channel_id is None
ah i forgot, also, im trying to fetch the guild channel id its currently talking in, and it keeps saying its invalid.
ctx.channel_id
correct?
@shrewd apex
you can see the possible attributes of ctx in the docs
!d discord.ext.commands.Context
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.
This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
How do I make my bot say something in a voice channel (For example, a simple message like "Hello") in a TTS voice without downloading any audio files?
is discord's built-in TTS good enough?
.send has a kwarg to enable it
What do you need, ask your question
commands.Context.channel then abc.Messageable.id
Maybe this is a little too open ended: I am completely new to python (and code in general) but I am trying to make a bot that will manage a spreadsheet. I havent had much luck so far as I cant even get the bot to respond to a message. Any advice would be appreciated :)
you should definitely make sure you're familiar with python before this project
discord.py is not for beginners, and id assume so with any spreadsheet lib
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
https://gist.github.com/scragly/095b5278a354d46e86f02d643fc3d64b#required-knowledge heres some details on what you should know
Learning discord.py. GitHub Gist: instantly share code, notes, and snippets.
Thank you
and uh can I ask why a spreadsheet?
Keeping track of a count for a small group of people across timezones is boring and Id rather have people be able to tell a bot to update the spreadsheet for me
If you want to store data, you'd use a database
Look for python tts packages in google
I think there are some
aiogtts looks good
Im not particularly familiar with any kinda of databases so I want to not overload myself with things to learn
yep, first go learn python, then the basics of dpy
thanks for the advice, I will go read things now
Why without downloading audio files?
If it's because you don't want to keep actual files in your machine, you can use an io buffer
(BytesIO)
You can just stream them into discord from URL
How so?
yeah but then how to convert it to an AudioSource ? Cuz VoiceClient object's play method only accepts an AudioSource object. I tried directly passing in a BytesIO object but it doesn't work
No. I'm building a bot for someone and my client insists on it speaking in the voice channel and not using TTS
Traceback (most recent call last):
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\view.py", line 390, in _scheduled_task
await item.callback(interaction)
File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\information\cog.py", line 191, in button_callback
await interaction.edit_original_message(embeds=[userinfo, embed_roles], view=self)
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\interactions.py", line 451, in edit_original_message
params = handle_message_parameters(
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\webhook\async_.py", line 537, in handle_message_parameters
payload["components"] = view.to_components()
AttributeError: 'Informations' object has no attribute 'to_components'
Ok and what is Informations
Is there a paste bin ?
!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.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Look at examples on nextcord's repo, you are not doing views correctly https://github.com/nextcord/nextcord/tree/master/examples%2Fviews
A Python wrapper for the Discord API forked from discord.py - nextcord/examples/views at master · nextcord/nextcord
Sure i use it correct. what you sent are examples.
Yeah examples to look at
You can also use the way I use
You should subclass instead of setting callbacks
Can doesn't mean should
But in this case it is easier
And anyways that's not the definition of Informations I asked for
Informationens is the class not more
it is obvious that the button is failing
What
I dont know what you want with the whole cog but here
https://paste.pythondiscord.com/oyuqusijuh
@white citrus
await interaction.edit_original_message(view=self)```
Causes the problems, in your case the `self` is the cog, this is why you should subclass views
Okay and?
Is there a way I can sync only role perms of a channel to it's category without overwriting user specific perms?
You are parsing object of wrong type to the kwarg, isn't it obvious? Wdym "okay and?", do you expect me to send the complete code or smth
but how
i want it to auto do it
I would only suggest a solution?
guys , can someone give me a overwrite code for :
everyone : read_messages = false
a role : read_messages = true
Do it yourself
I suggested it: subclass instead of your way. Although you can view=nextcord.View.from_message(interaction.message) but it's a pretty bad method. Why are you so stubborn about subclassing?
If you don't want to create a separate class for everything you could do sort of generic class, I can send you the example as well
how to remove timeout?
!d discord.Member.timeout just set the duration to None
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").
You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") to do this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
sup brother
You aren't commiting it.
yep
Also in the future this is a #databases question.
I said yep to cursor btw you don't commit to conn.
Any errors?
Hi can i get user info source?
how can i check a json file for members ?
or how can i print all of those members in a message
?
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.
hash(x) Returns the member’s hash.
str(x) Returns the member’s name with the discriminator.
Can I get user info with this code?
pls help
i just want to add something like a word to a json file and than with another command i want to send that in a message
but that with multiple things
i need help adding and loading them
here is the json file code
{
"userid": {
"Kicked": true,
"Name": "Someoneelse"
},
"userid2": {
"Kicked": true,
"Name": "Someone"
}
}
``` so the userid is the user its id and than some info about it now my question is how can i send that info in a message ?
you used to be able to load them without having async and nkw you do. and i don't know how i should approach that
of all of the user ids
if you do not understand what i mean pls tell me i just want to know HOW i do it
if "ticket-"+ member.name +"." in ctx.channel.name: why this dont work
is it possible to delete last message on specific channel?
where you create your invites table, you have set the id column to be an integer, but invite.id is not an integer
no. invite.id is a string
property id```
Returns the proper code portion of the invite.
can someone help me
change your invite.id column to a string
Then check their docs for what type it is
go to the place in your code you are creating the invite table
and change the column type
you maybe need to write a migration to change any existing databases, if you don't want to delete the database and start over
How long does it take to these goddamn slash commands to appear?
I don't know what program that is, but you should be able to google "<program name> change mysql column to string" to get the answer
depends, did you create the database in your code?
then go back and do this
and read this
which part of that is setting the id column to bigint?
cool, and how would you change that to make it text?
yup
but that will only work the next time the database is created
CREATE TABLE IF NOT EXISTS means it will only run if a database doesn't already exist
Sure
An hour unless you manually synchronize them with a guild
Can you tell me how to manually synchronize please?
Can you tell me what library are you using
Uh, hold on
!d discord.app_commands.CommandTree.sync
await sync(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Syncs the application commands to Discord.
This also runs the translator to get the translated strings necessary for feeding back into Discord.
This must be called for the application commands to show up.
HELP ME PLS
@dry fox you got to pass a discord.Object object with the id of the guild (if you have a discord.Guild object, that works too) and await it
i think this advice has been outdated since i didnt have to wait that long for a global command update, but the only resource i found supporting this was a PR removing the one hour disclaimers from the API docs
https://github.com/discord/discord-api-docs/pull/4896
pls help
Press X to Doubt
I imagine they have an hourly loop that updates application commands so it's up to an hour at most but can take less than so
I have both slash command and echo And The slash commands doesn't show up but the echo works so the bot works
that PR, along with a related one by disnake https://github.com/DisnakeDev/disnake/pull/518 calls it "commands v2", so it does seem a new architecture was rolled out for rolling out app commands
Is it just an automated thing done by the library
the synchronization?
Add some debug logging to your command that adds the invite to see what's going on
Yes
a followup PR 3 months later removed the android disclaimer https://github.com/discord/discord-api-docs/pull/5398
nah this is part of discord's backend
pls help
NameError: name 'bot' is not defined
if "ticket-"+ member.name +"." in ctx.channel.name: why this dont work
hello who can help me for my bot please
and this was not for you
Question:
How can i send a message that contains all the data from a json file in little pieces?
Example:
{
"16131694321986341": {
"Kicked": true,
"Name": "Albert"
},
"6546541454857564": {
"Kicked": true,
"Name": "Bert"
}
}``` How can i make it so that i get the information from "Albert" and "Bert" in 1 message ?
**My code that doesnt work:**
```python
def add_kick(member: discord.Member, id: int):
if os.path.isfile(f"servers/kick{id}.json"):
with open(f"servers/kick{id}.json", "r") as fp:
data = json.load(fp)
try:
data[f"{member.id}"]["Name"] = member.name
data[f"{member.id}"]["Kicked"] = True
except KeyError:
data[f"{member.id}"] = {"Name": member.name}
data[f"{member.id}"] = {"Kicked": True}
else:
data = {f"{member.id}": {"Name": member.name}}
data = {f"{member.id}": {"Kicked": True}}
with open(f"servers/kick{id}.json", 'w+') as fp:
json.dump(data, fp, sort_keys=True, indent=4)
@bot.command()
async def kick(ctx, member: discord.Member):
add_kick(member, ctx.guild.id)
add_kick(member, ctx.guild.id)
await ctx.send(f"ok")
@bot.command()
async def getkick(ctx):
with open(f"servers/kick{ctx.guild.id}.json", "r") as fp:
data = json.load(fp)
name = data[f"{ctx.author.id}"]["Name"]
kicked = data[f"{ctx.author.id}"]["Kicked"]
await ctx.send(f"{name} {kicked}")``` Please help me
hi, is there a way to @mention someone without him getting a notification? (In normal messages, not embeds)
for you or the bot ?
i think for the bot you can just do somthing like this (f"@{user.name}")
i dont think that will mention the user
Yeah set the allowed_mentions kwarg
!d discord.abc.Messageable.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=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/latest/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.10)") of [`File`](https://discordpy.readthedocs.io/en/latest/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/latest/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.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
!d discord.AllowedMentions
class discord.AllowedMentions(*, everyone=True, users=True, roles=True, replied_user=True)```
A class that represents what mentions are allowed in a message.
This class can be set during [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") initialisation to apply to every message sent. It can also be applied on a per message basis via [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for more fine-grained control.
Behold my latest creation https://paste.pythondiscord.com/oxitofijas
Make sure you used the same env for installing and running, you can check it at the bottom right corner
This thing moves everyone from the channel when certain user joins? Sus
That's gonna look funny tho
It does lol
This isn't getting much attention because you are using json as a method of keeping track of things. JSON isn't meant to dynamically change data but rather static, and since you're also in an async environment opening and closing files is considered a heavy sync task.
ok what else can i do ?
I recommend getting started with databases, your code looks fine so I don't think it should be an issue for you.
what can i use as databases ?
I personally recommend postgresql paired with asyncpg or a file based sql called sqlite paired with aiosqlite.
If you are more fan of the 'json' syntax I recommend mongoDB paired with motor.
i do not understand what you are saying but uhm where can i begin ?
I'm saying that you shouldn't use JSON to store data.
ah ok
but do you know a good video that explainsµ all of this ?
I got docs :3
nah i suck at reading them i cant figure out what they mean in that
This vid explains it a bit -> https://www.youtube.com/watch?v=b9_PQvu7UWM
I recommend muting it tough.
ok
ah yes i understand why
everybody has a different preference on learning stuff
what is intensts
!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 Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, 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.
why do you care just do not
Started using async with mongodb and suddenly the 300k lines tracebacks disappeared
lol
Can blocking code end up causing ratelimits?
Maybe the bot tries to reconnect too many times?
maybe
The opposite
It'll block things like heartbeats and get you disconnected
possibly
You weren't supposed to say this, I was going to start a discussion about memory types 🤓
?
Code:
@commands.group(invoke_without_command=True)
async def welcome(self, ctx):
await ctx.send("Allowed: \nchannel <#channel> \ntext <message>")
@welcome.command()
async def channel(self, ctx, channel: discord.TextChannel):
if ctx.message.author.guild_permissions.manage_messages:
db = sqlite3.connect("main.sqlite")
cursor = db.cursor()
cursor.execute(f"SELECT channel_id FROM main WHERE guild_id = {ctx.guild.id}")
result = cursor.fetchone()
if result is None:
sql = ("INSERT INTO main(guild_id, channel_id) VALUES(?)")
val = (ctx.guild.id, channel.id)
await ctx.send(f"Channel is set to {channel.mention}")
elif result is not None:
sql = ("UPDATE main SET channel_id = ? WHERE guild_id = ?")
val = (channel.id, ctx.guild.id)
await ctx.send(f"Channel is updated to {channel.mention}")
cursor.execute(sql, val)
db.commit()
cursor.close()
db.close()
Error:
discord.ext.commands.errors.CommandNotFound: Command "welcome" is not found
?
how are you invoking the command
huh ?
how are you using the command
idk ? what do you mean
never mind then
that should be invoked like ?welcome channel channel
uhm
wait i have image of what it would look like
some other words but you see it
try doing ?welcome channel #somechannel
that's how your code is supposed to work
oh ok
replace it with whatever your prefix is
says that Welcome is not found
send the terminal
did you call your bot commands ?
no
What did you call the class
it should be @bot.group
object oriented programming
then what happened?
and got this
no ?
It's recommended you understand it before trying to make discord bots, they aren't beginner level projects
?
async def channel(self, ctx, *, channel: discord.TextChannel):
try that in the channel command
ok
same problem
send the code u used now
!d discord.TextChannel
class discord.TextChannel```
Represents a Discord guild text channel.
x == y Checks if two channels are equal.
x != y Checks if two channels are not equal.
hash(x) Returns the channel’s hash.
str(x) Returns the channel’s name.
?
stop with the question marks
but what am i with this ❓
nothing
ok so uhm ?
uhhh
Ive never used subcommands
same
send ur code again
maybe we can make it 1 command
no
what happens when you do ?welcome
remove self
it worked BUT BUT BIG BUT
calm down
it should not have the @bot decorators, if in cog
remove the * I told you to put
I use a discord channel as db
ok
and that's probably sql error idk how to fix
same error
Idk how to fix
you said you made a discord channel a database right
don't do that...
it's private bot
ok
class discord.TextChannel```
Represents a Discord guild text channel.
x == y Checks if two channels are equal.
x != y Checks if two channels are not equal.
hash(x) Returns the channel’s hash.
str(x) Returns the channel’s name.

