Why is Async function not being executed in python - python

import discord
intent=discord.Intents.default()
intent.members=True
client=discord.Client()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_member_join(member):
guild=client.get_guild(ServerID)
channel=guild.get_channel(ChannelID)
await channel.send(f'Welcome to the server{member.mention}! :D')
await member.send(f'Welcome to the {guild.name} server,{member.name}! :D')
print(f'Welcome to the {guild.name} server,{member.name}! :D')
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
Why is my join function not being executed when someone joins my discord server ?
i have given all the permission as well that is needed to msg in the specific channel
but it seems that it never even calls the function
Edit: I changed it to on_member_join it still doesn't work

Your code for creating your client isn't complete. You have to assign the intents along with it, such as down below.
client=discord.Client(intents = intent)
In fact, I would recommend you look at the bot part of the discord.py documentation in order to setup the client with the necessary attributes for a discord bot.
(Also I'm going to assume you have the variables of ServerID and ChannelID saved somewhere else in the code, I just wanted to help the issue of triggering the on_member_join at all).

join is an invalid event listener name in discord.py. Try changing the function's name to on_member_join.

Related

why I can't receive messages through a separate function for my discord bot

import discord
import mysql.connector
client = discord.Client(intents=discord.Intents.all())
mylb = mysql.connector.connect(
host='localhost',
user='root',
password="",
database="worst")
cursor = mylb.cursor()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
async def spam(message):
if message.author == client.user:
return
if message.content.startswith('$long'):
await message.channel.send("spam")
client.run('my token')
In this code when I type $hello I am successfully getting the output of hello but when I type $long which is in another function I am not able to get the output of spam. Pls help me to resolve my issue. I would be thankfull to you.
I think there's a distinct lack of understanding of concepts here.
Typing $hello works as it's on the on_message function; which with the #client.event registers it as a listener for whenever a message is sent in Discord. The library is calling this function and executing your code every time someone sends a message.
With your second command - this is not the case. You're not calling the spam function anywhere so there's no reason why it should be doing anything. Your code is working exactly as it's written.
It would be better to expand the on_message function to contain this functionality:
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
elif message.content.startswith('$long'):
await message.channel.send("spam")
HOWEVER, it's probably better to use some kind of framework (like the commands framework) for what you're trying to do. You haven't mentioned a library - so assuming you're using discord.py - then the docs are here. There's functionality built into the library to already parse messages for the given prefix and registered commands (you could register your hello and long commands) and this would invoke separate functions where you can have your logic rather than trying to do it all yourself in on_message.
Perhaps read some tutorials online about Python and making discord bots - there's a couple of fundamental concepts you should get to grips with first.
EDIT: If you really don't want to use existing frameworks then perhaps something like this:
async def hello(message):
# do whatever else you want to do in here
await message.channel.send("Hello!")
async def long(message):
# do whatever else you want to do in here
await message.channel.send("spam!")
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await hello(message)
elif message.content.startswith('$long'):
await long(message)

My discord bot isn't throwing any error but it's not responding to anything either

So, basically i was trying to make a bot for discord using python and this is my first project so i was trying out new stuffs
here's my code
import discord
from http import client
from discord.ext import commands
client = discord.Client()
client = commands.Bot(command_prefix='`')
#client.event
async def on_ready():
print("Bot is online")
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content == 'hello':
await message.channel.send('Welcome to the server, human')
#client.command
async def info(ctx):
await ctx.send(ctx.guild)
client.run(#mytokenishereicantshareit)
as you can see i am completely new to programming in general, so if you may help me out, the bot is saying "Bot is online" in output and it's getting online in my server its not showing any errors either. but it's none of my commands are working, like the "hello" and `info.
Edit : This issue has been fixed, There are two possible solutions for this either you can replace the #client.event with #client.listen or just add a await bot.process_commands(message) after
if message.content == 'hello':
await message.channel.send('Welcome to the server, human')
Part like
if message.content == 'hello':
await message.channel.send('Welcome to the server, human')
await bot.process_commands(message)
and you're done.
Firstly, remove the client = discord.Client() bit because the bot already does that, and secondly, add a bracket after the #client.command so it's #client.command()

How do i get a discord bot to make and assign roles using Discord.py?

I want to make a bot that makes and assigns a role to the person who requested it. How do I do that? I have tried many things but they all don't work. Here is a copy of the non-functioning code.
import discord
import os
from discord.utils import get
client = discord.Client()
#client.event
async def on_ready():
print ('we have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('~hello?'):
await message.channel.send('YOU WILL NOW WISH YOU NEVER SUMMONED ME...')
client.run(os.environ['TOKEN'])
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content == ('~begin?'):
role = get(message.server.roles, name=('Admin'))
await client.add_roles(message.author, role)
client.run(os.environ['TOKEN'])
The first part works (~hello?) but the second part (~begin?) doesn't work. Can one of you gracious souls save me from this endless tussle of debugging and coding?
You can add a command using the #client.command function, but first you need to add a prefix to `client by doing
client = commands.AutoShardedBot(commands.when_mentioned_or(*prefix*))
remember to import commands using from discord.ext import commands
then your life would be easy now, if you want to add a command just do
#client.command
async def add_role(ctx, member:discord.Member):
role = get(ctx.guild.roles, name='*the role*')
await member.add_roles(role)
so to call the command just say *prefix* add_role #*the user*
I see a few mistakes in your code.
To get back to your question:
If you want to get the role in a server you have to request the guild, server is kind of outdated. In code this means the following:
role = message.guild.roles.
Reference: Message.guild
After getting the role we have to assign it to a member, this does not work with client.add_roles, try message.author.add_roles() instead. It'll be await message.author.add_roles(role) in the long version then.
If you want to assign a role to a member through your bot you also need to enable Intents. There are tons of Contributions on this site but also in the docs, for example:
Docs
How to get intents to work?

discord.py: Why isn't my join message working?

I am stumped on why my join message isn't working! I have the discord.py library installed, and I am really confused! I have other code below it, but it shouldn't effect the above.
import discord
client = discord.Client()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_member_join(member):
print("Player has joined")
channel = await client.fetch_channel(800395922764070942)
await channel.send(f'{member} has joined!')
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!loser'):
await message.channel.send('Hello loser! Nice to meet you.')
elif message.content.startswith('!bruh'):
await message.channel.send('BRUHHHHHHHHHHHHHHH!!!!')
client.run("Where my token is")
Edited to show entire code. (Sorry for the stupid bruh things, they run perfectly but I just wanted to test some things..)
Due to recent changes in discord.py (1.5.0) you now need to use intents. Intents enable to track things that happen.
First you need to enable it on the developer portal (where you created your bot). When you're there, select your application, go to the bot section, scroll down and tick the box.
Then in your code you need to add this at the top :
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
You will now be able to receive events like on_member_join.
Have you tried changing the get_channel line from
channel = client.get_channel(800395922764070942)
to
channel = await client.fetch_channel(800395922764070942)

discord.py bot isn't answering when mentioned from phone app

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

Categories