I am trying to send a message to a specific channel and I can run the code below just nothing show up on the channel and I have no idea why... I put the channel Id in the get_channel input, just putting a random number here.
import discord
client = discord.Client()
async def send_msg(msg):
channel = client.get_channel(123456456788)
await channel.send('hello')
Is the function even called somewhere? Otherwise there could also be an issue with the discord permissions or the Intents.
This is one of many ways to call the function and post 'hello' in some specific channel. No msg parameter is required.
#client.event
async def on_ready():
await send_msg()
async def send_msg():
channel = client.get_channel(123456456788)
await channel.send('hello')
Related
So i was writing a simple discord bot where when an user join it would simply send a message in the main channel saying something like hello user. Everything was working, at first i printed that a user joined on the console and everything worked. Then i tried to do it in a channel by using channel = client.get_channel("my channel here") await channel.send("Hello") but it's not working as intended. So i was wondering if there was a way to do this.
(Btw this is my first stackoverflow question, so if there's anything i did wrong pls let me know)
Here is the Full code:
from discord.ext import commands
intents = discord.Intents()
intents.members = True
client = commands.Bot(command_prefix='!', intents = intents)
#client.event
async def on_ready():
print("The bot logged on")
print("-----------------")
#client.event
async def on_member_join(member):
print("Somebody joined")
channel = client.get_channel(my channel here)
await channel.send("Hello")
client.run("MY token")
And here is the error:
AttributeError: 'NoneType' object has no attribute 'send'```
You need to await fetch, because the cache might not have the channel in there when the member joins. Your coroutine error comes from not awaiting it. (An unexecuted coroutine object gets assigned to channel, and then you get an error when it tries to call that because it was "already called".)
#client.event
async def on_member_join(member):
print("Somebody joined")
channel = await client.fetch_channel(123456789)
await channel.send("Hello")
Goal:
I am simply trying to send a message to a discord channel from a #tasks.loop() without the need for a discord message variable from #client.event async def on_message. The discord bot is kept running in repl.it using uptime robot.
Method / Background:
A simple while True loop in will not work for the larger project I will be applying this principle to, as detailed by Karen's answer here. I am now using #tasks.loop() which Lovesh has quickly detailed here: (see Lovesh's work).
Problem:
I still get an error for using the most common method to send a message in discord using discord.py. The error has to have something to do with the await channel.send( ) method. Neither of the messages get sent in discord. Here is the error message.
Code:
from discord.ext import tasks, commands
import os
from keep_alive import keep_alive
import time
token = os.environ['goofyToken']
# Set Up Discord Client & Ready Function
client = discord.Client()
channel = client.get_channel(CHANNEL-ID)
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#tasks.loop(count=1)
async def myloop(word):
await channel.send(word)
#client.event
async def on_message(message):
msg = message.content
if msg.startswith('!'):
message_to_send = 'Hello World!'
await channel.send(message_to_send)
myloop.start(message_to_send)
keep_alive()
client.run(token)
Attempted Solutions:
A message can be sent from the on_message event using the syntax await message.channel.send('Hello World!). However, I just can't use this. The code is kept running online by uptimerobot, a free website which pings the repository on repl.it. When the robot pings the repository, the message variable is lost, so the loop would stop scanning my data in the larger project I am working on which is giving me this issue.
When using any client.get_* method the bot will try to grab the object from the cache, the channel global variable is defined before the bot actually runs (so the cache is empty). You should get the channel inside the loop function:
#tasks.loop(count=1)
async def myloop(word):
channel = client.get_channel(CHANNEL_ID)
await channel.send(word)
I made recently a discord bot for small server with friends. It is designed to answer when mentioned, depending on user asking. But the problem is, when someone mention bot from a phone app, bot is just not responding. What could be the problem?
Code:
import discord
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
bot = commands.Bot(command_prefix = '=')
reaction = "🤡"
#bot.event
async def on_ready():
print('Bot is ready.')
#bot.listen()
async def on_message(message):
if str(message.author) in ["USER#ID"]:
await message.add_reaction(emoji=reaction)
#bot.listen()
async def on_message(message):
mention = f'<#!{BOT-DEV-ID}>'
if mention in message.content:
if str(message.author) in ["user1#id"]:
await message.channel.send("Answer1")
else:
await message.channel.send("Answer2")
bot.run("TOKEN")
One thing to keep in mind is that if you have multiple functions with the same name, it will only ever call on the last one. In your case, you have two on_message functions. The use of listeners is right, you just need to tell it what to listen for, and call the function something else. As your code is now, it would never add "🤡" since that function is defined first and overwritten when bot reaches the 2nd on_message function.
The message object contains a lot of information that we can use. Link to docs
message.mentions gives a list of all users that have been mentioned in the message.
#bot.listen("on_message") # Call the function something else, but make it listen to "on_message" events
async def function1(message):
reaction = "🤡"
if str(message.author.id) in ["user_id"]:
await message.add_reaction(emoji=reaction)
#bot.listen("on_message")
async def function2(message):
if bot.user in message.mentions: # Checks if bot is in list of mentioned users
if str(message.author.id) in ["user_id"]: # message.author != message.author.id
await message.channel.send("Answer1")
else:
await message.channel.send("Answer2")
If you don't want the bot to react if multiple users are mentioned, you can add this first:
if len(message.mentions)==1:
A good tip during debugging is to use print() So that you can see in the terminal what your bot is actually working with.
if you print(message.author) you will see username#discriminator, not user_id
I'm making a discord bot and I want it to send a message whenever it joins a new guild.
However, I only want it to send the message in the #general channel of the guild it joins:
#client.event
async def on_guild_join(guild):
chans = guild.text_channels
for channel in chans:
if channel.name == 'general':
await channel.send('hi')
break
The problem that I have noticed is that guild.text_channels only returns the name of the very first channel of the server. I want to iterate through all channels and finally send message only on the #general channel.
What's the workaround for it?
There are a couple ways you can do this.
Here's an example using utils.get():
import discord # To access utils.get
#client.event
async def on_guild_join(guild):
channel = discord.utils.get(guild.text_channels, name="general")
await channel.send("Hi!")
Or if the guild has a system_channel set up, you can send a message there:
#client.event
async def on_guild_join(guild):
await guild.system_channel.send("Hi!")
You can create checks for both of these, but bear in mind that some servers might not have a text channel called general or a system channel set up, so you may receive some attribute errors complaining about NoneType not having a .send() attribute.
These errors can be avoided with either an error handler or a try/except.
References:
Guild.system_channel
utils.get()
I have been trying to create a bot for Discord using the discord.py library however when I am running the program it is not sending the message as expected. It is a simple bot that is suppose to send a message every 10 minutes to a channel. I am not getting any error messages in the command line and can't seem to see any obvious errors? Any help would be greatly appreciated.
import asyncio
client = discord.Client()
async def my_background_task():
await client.wait_until_ready()
counter = 0
channel = discord.Object(id='my channel ID goes here')
while not client.is_closed:
counter += 1
await message.channel.send("TEST")
await asyncio.sleep(5) # task runs every 60 seconds
#client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
client.loop.create_task(my_background_task())
client.run('My token goes here')
Although creating a task could work, I wouldn't recommend it when there are better options. Dpy's command.ext addon has a task based system built in directly, so let's look into using that instead.
import discord
from discord.ext import tasks
client = discord.Client()
#tasks.loop(minutes=10)
async def my_background_task():
"""A background task that gets invoked every 10 minutes."""
channel = client.get_channel(754904403710050375) # Get the channel, the id has to be an int
await channel.send('TEST!')
#my_background_task.before_loop
async def my_background_task_before_loop():
await client.wait_until_ready()
my_background_task.start()
client.run('Your token goes here')
The time until which the above loop will run is dependent upon human psychology, laws of energy and cosmos.
That is:
• You get bored of it
• The power goes down and your script stops working
• The universe explodes
Read more about it here:
https://discordpy.readthedocs.io/en/latest/ext/tasks/
If the channel ID is a string, It should be an integer.
Turn this:
channel = discord.Object(id='my channel ID goes here')
into:
channel = discord.Object(id=101029321892839) # an example ID
If that doesn't solve your problem, try setting 'message.channel.send' to 'channel.send' and client.is_closed should be
client.is_closed() # put brackets
Instead of client.loop.create_task(my_background_task()), just put the background function in the on_ready event. And take out await client.wait_until_ready() and just put the function in the on_ready event as well.
I have also changed the client variable, taken out unnecessary code, and added some modules.
import asyncio, discord
from discord.ext import commands
client = commands.Bot(command_prefix = ".") # If you don't want a prefix just take out the parameter.
async def my_background_task():
channel = discord.Object(id='my channel ID goes here')
while True:
await channel.send("TEST")
await asyncio.sleep(5) # task runs every 60 seconds
#client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
my_background_task()
client.run('My token goes here')
Also in future when posting a question, please tag the python version as I don't know which version it is and then this and other answers could be wrong.