'variable is empty even after using global to make it global scoped
I want my program to welcome someone as soon as they join a discord server (discord.py), and that part works fine. However, to get the guild name, my program sends a message in a channel, and then it checks if it sent the message in the required channel and gets the guild name from there using message.guild.name
. now for this to work, it needs to be global scoped because i have two functions in my code, one being on_message
and the other being on_member_join
. Somehow, it works without an error but when it's sending the welcome message, it just registers the guild name as an empty string. Why?
Here's my code for more clarity:
client = discord.Client()
serverName = ""
@client.event
async def on_message(message):
if message.content.lower() == "a new member has arrived" and message.author == client.user:
global serverName
serverName = message.guild.name
@client.event
async def on_member_join(member):
embed = discord.Embed(title="Welcome to " + serverName) #here it shows the initially declared empty string.
await member.send(embed=embed)
await client.get_channel(channelId).send("A new member has arrived")
Solution 1:[1]
You don't need to send a message to get the guild name.
On member join there is a discord.Member
parameter which is a member of the guild. there u can get the guild name by member.guild.name
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Yash Verma |