pinging multiple users in discord bot - python

I am trying to "#" specific members after issuing a command, the following doesn't seem to work.
from tokens.token import discord_token
from discord.ext import commands
from discord.utils import get
intents = discord.Intents(messages=True, guilds=True)
client = commands.Bot(command_prefix="!",intents = intents)
#client.event
async def on_ready():
print("Bot is ready!")
#client.command
async def play(ctx):
paul = get(ctx.guild.members, name = 'paul')
john = get(ctx.guild.members, name = 'john')
await ctx.send("f{paul.mention} {john.mention} lets play games!")
client.run(discord_token)
It should return something like
MyBotName: #john #paul lets play games!
Thanks!

You have used f-string wrong in your code. f must be come before the string:
await ctx.send(f"{paul.mention} {john.mention} lets play games!")✅
await ctx.send("f{paul.mention} {john.mention} lets play games!")❌
Also if you didn't enable intents, go to the developer portal and enable intents. Then add it to your bot's properties with:
bot = commands.Bot(command_prefix="!", discord.Intents.all()) # or what you need

Related

Discord.py Commands Unresponsive

I am trying to make a bot with a simple function of creating a channel, but it is unsuccessful.
Here's my code:
import os
import discord
from keep_alive import keep_alive
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
client = discord.Client(intents=intents)
bot = commands.Bot(command_prefix='$',intents=intents)
guild = discord.Guild
#client.event
async def on_ready():
print("I'm in as " + str(client.user))
#bot.command(name = "hack")
async def court_create(ctx, msg):
print("Received: $hack") #output to console
channel_name = "hack-" + str(msg)
await ctx.send(channel_name) #output to channel
channel = await guild.create_text_channel(name = channel_name)
keep_alive()
Token = os.environ['Token']
client.run(Token)
Note that for debugging, I added two lines so that when it receives the command, it prints out to both the console and the channel. However, when I typed $hack 123 into the channel, it did nothing, not even outputting Received: $hack. Any ideas about this?
Bot has manage channel permission.
#bot.command(name = "hack")
async def court_create(ctx, msg):
The name in bot.command and the name of the function are two completely different names. It only reads what the function name is. If you want to add hack as another method of using the command you can use the aliases argument in bot.command()
Example:
#bot.command(aliases=["hack"])
async def court_create(ctx, msg):

Simple Discord Python Bot Err0r

apparently I am creating a simple discord reply bot and I have an error with my code. Even if I say the correct word with $ in chat, it is still using and replying to me with the else statement. I do not have this problem on the replit, but I do on my home PC, what could be the problem?
import discord
import os
from dotenv import load_dotenv
client = discord.Client(intents=discord.Intents.default())
load_dotenv()
TOKEN = 'TOKEN'
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send("Hello World!")
else:
await message.channel.send("Hello World! BUT ERROR")
#client.event
async def on_connect():
print("Bot Connected")
client.run(TOKEN)
enter image description here
Your bot does not have the Message Content Intents, so it will not be able to read messages sent by users.
In discord.py 2.0, a bot must have the Message intent in order to read messages' content.
To enable Message Intents for your bot, follow these steps:
Go to Discord's developer portal and click on your application's name.
Click on "Bot" in the sidebar.
Scroll down until you see "Privileged Gateway Intents".
You should see the option named "Message Content Intent". Enable it.
The next step:
At the start of your bot code, you should have a line of code that creates a Client or Bot object, for example:
client = discord.Client() or bot = discord.Bot(...)
First, you should define a variable intents:
intents = discord.Intents.all() # define intents
Now, add the parameter intents to the object, like this:
client = discord.Client(intents=intents)
or:
bot = discord.Bot(..., intents=intents)
And you are all set!
Hope this helped.
If I understood your question correctly. I suggest that you use the following code instead.
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.lower() == '$hello':
await message.channel.send("Hello World!")
else:
await message.channel.send("Hello World! BUT ERROR")
What I have changed here is using the string matching instead of startswith() function.

How to stop repetitive messages, and the token is changed, but it doesn't run

I started learning python today and made a Discord bot. I have a few problems:
If message.author == was used in the on_message, but the bot continued to reply to itself.
Afterwards, a new bot was created with a new token and the code didn't work.
I searched a lot on this site and Google. I didn't find any solution. It's okay to modify my code. Everything is from the internet, so it can be a mess. Please help me.
import discord
import asyncio
from discord.ext import commands
client = discord.Client()
bot = commands.Bot(command_prefix="!")
#bot.event
async def on_ready():
print('Loggend in Bot: ', bot.user.name)
print('Bot id: ', bot.user.id)
print('connection was succesful!')
print('=' * 30)
#client.event
async def on_message(message) :
if on_message.content.startswith('!의뢰'):
msg = on_message.channel.content[3:]
embed = discord.Embed(title = "브리핑", description = msg, color = 0x62c1cc)
embed.set_thumbnail(url="https://i.imgur.com/UDJYlV3.png")
embed.set_footer(text="C0de")
await on_message.channel.send("새로운 의뢰가 들어왔습니다", embed=embed)
await client.process_commands(message)
client.run("My bot's token.")
Your code was messy, but it should work now. I included comments to let you know how everything works. I think the good starting point to making your own bot is reading documentation. Especially Quickstart that shows you a simple example with explanation.
Write !example or hello to see how it works.
import discord
import asyncio
from discord.ext import commands
# you created 'client' and 'bot' and used them randomly. Create one and use it for everything:
client = commands.Bot(command_prefix="!") # you can change commands prefix here
#client.event
async def on_ready(): # this will run everytime bot is started
print('Logged as:', client.user)
print('ID:', client.user.id)
print('=' * 30)
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('hello'): # you can change what your bot should react to
await message.channel.send("Hello! (This is not a command. It will run everytime a user sends a message and it starts with `hello`).")
await client.process_commands(message)
#client.command()
async def example(ctx): # you can run this command by sending command name and prefix before it, (e.g. !example)
await ctx.send("Hey! This is an example command.")
client.run("YOUR TOKEN HERE")

change discord.py bot status

it may hard to me, but i believe on stackoverflow power,
i need to put a number as bot status on my bot.
Here : http://gamers-control-2.000webhostapp.com/count.txt
Also Pic of it : Picture
#time to show status = text that founded in blank website = "41"
#http://gamers-control-2.000webhostapp.com/count.txt
#some how, you say i can type the number, i say the number in web it
change everytime, so i need to get that number to show it as bot status.
import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
import time
import random
from discord import Game
Client = discord.client
client = commands.Bot(command_prefix = '!')
Clientdiscord = discord.Client()
#client.event
async def on_ready():
await client.change_presence(game=discord.Game(name=http://gamers-control-2.000webhostapp.com/count.txt, type=3))
print('test ready')
client.run("....")
im new with discord.py
You need to first import requests at the beginning
import requests
Then before the ready event
count = requests.get('http://gamers-control-2.000webhostapp.com/count.txt')
And then you set it to
await client.change_presence(game=discord.Game(name=count.text, type=3))
I use await bot.change_presence() like this:
NOTICE:
I am leaving out part of my code
#bot.event
async def on_ready():
replit.clear()
print(f'Logged in as {bot.user.name} - {bot.user.id}')
bot.remove_command('help')
await bot.change_presence(status=discord.Status.online, activity=discord.Game("mod help"))
This is what i use
async def on_ready():
print(f'We have logged in as {bot.user}')
print('Ready!')
return await bot.change_presence(activity=discord.Activity(type=3, name='Add status here'))```

Improper token passed

I'm following a basic tutorial for a Python Discord bot on YouTube and my code is underneath. It says:
discord.errors.LoginFailure: Improper token has been passed.
Before anyone asks, yes I have put in the bot token, not the id or secret.
import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
import time
Client = discord.Client()
client = commands.Bot(command_prefix = "!")
#client.event
async def on_ready():
print("Bot is ready!")
#client.event
async def on_message(message):
if message.content == "cookie":
await client.send_message(message.channel, ":cookie:")
client.run("token is here")
For me, my bot.py file looks like this:
import os
import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
client = discord.Client()
#client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
client.run(TOKEN)
and since I used env (environment) modules, I created a new file with an empty name and with the .env extension in the same path in a folder. The env file only has this line of code:
DISCORD_TOKEN=DFHKJAhka7fdsKHJASDFk1jhaf5afd.HASDFafd23FHdfa_adfahHJKADF32W
So the problem for me was I was using brackets around the token code and after I removed it, it worked!
My code when it had brackets:
DISCORD_TOKEN={DFHKJAhka7fdsKHJASDFk1jhaf5afd.HASDFafd23FHdfa_adfahHJKADF32W}
Make sure you grab the "Token" from the "Bot" page in the Discord development site, rather than the "Secret" from the "General Information" page.
I was having the same problem. My issue was solved by using the correct token from the Discord app page. I was using the "Secret" from the 'General Information' page (which generated the error in the original post for me) instead of the "Token" from the "Bot" page.
As sheneb said in the comment to this, this answer (probably) won't help the OP (since the question now says "Before anyone asks, yes I have put in the bot token, not the id or secret"). However, I found this question/page when searching for the answer, and my issue was solved with this information.
The same thing happened to me, but it started working when I went to the developer page and refreshed the token. Then I just put the new token in the code and it worked!
Maybe the same will work for you...?
You should be able to get it to work by doing this:
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
import time
Client = discord.Client()
client = commands.Bot(command_prefix = "!")
#client.event
async def on_ready():
print("Bot is ready!")
#client.event
async def on_message(message):
if message.content == "cookie":
await message.client.send(":cookie:")
client.run("token is here", bot=True)
I do this sometimes, but also, check to make sure you have fully created your bot by taking a look at the "bot" tab on your developer page.
I also made a fix for your message send line. It was out of date ;).
Try this:
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
import time
Client = discord.Client()
client = commands.Bot(command_prefix = "!")
#client.event
async def on_ready():
print("Bot is ready!")
#client.event
async def on_message(message):
if message.content == "cookie":
await message.client.send(":cookie:")
client.run("TOKEN HERE. PUT YOUR TOKEN HERE ;)")
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
import time
Client = discord.Client()
client = commands.Bot(command_prefix = "!")
#client.event
async def on_ready():
print("Bot is ready!")
#client.event
async def on_message(message):
if message.content == "cookie":
await message.client.send(":cookie:")
client.run("PUT YOUR TOKEN HERE")

Categories