Discordpy welcome bot - python-3.x

So, i tried to make a bot that send embed to specific channel everytime user join my server.
The code is look like this
import discord
import asyncio
import datetime
from discord.ext import commands
intents = discord.Intents()
intents.members = True
intents.messages = True
intents.presences = True
bot = commands.Bot(command_prefix="a!", intents=intents)
#bot.event
async def on_ready():
print('Bot is ready.')
#bot.event
async def on_member_join(ctx, member):
embed = discord.Embed(colour=0x1abc9c, description=f"Welcome {member.name} to {member.guild.name}!")
embed.set_thumbnail(url=f"{member.avatar_url}")
embed.set_author(name=member.name, icon_url=member.avatar_url)
embed.timestamp = datetime.datetime.utcnow()
channel = guild.get_channel(816353040482566164)
await channel.send(embed=embed)
and i got an error
Ignoring exception in on_member_join
Traceback (most recent call last):
File "C:\Users\Piero\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Piero\Documents\Discord\a-chan\achan_bot\main.py", line 24, in on_member_join
channel = guild.get_channel(816353040482566164)
NameError: name 'guild' is not defined
Anyone know what is wrong in my code?

First of all, looking at the discord.py documention, ctx is not passed to the on_member_join event reference. However, you can use the attributes of member which is passed in order to get the values which you need.
#bot.event
async def on_member_join(member):
embed = discord.Embed(
colour=0x1abc9c,
description=f"Welcome {member.name} to {member.guild.name}!"
)
embed.set_thumbnail(url=f"{member.avatar_url}")
embed.set_author(name=member.name, icon_url=member.avatar_url)
embed.timestamp = datetime.datetime.utcnow()
channel = member.guild.get_channel(816353040482566164)
await channel.send(embed=embed)
Interestingly enough, you did this perfectly for getting the guild name, but it seems you forgot to do the same when retrieving channel.

You did not define guild.
To define your guild you can do the following:
guild = bot.get_guild(GuildID)
It's the same method you used to define your channel, just for your guild now.
For further information you can have a look at the docs: https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.get_guild
Also take into account that we do not have a paramter like ctx in an on_member_join event.
The event just has the parameter member in your case:
#bot.event
async def on_member_join(member): #Removed ctx

Related

Pycord mute command doesn't throw error but doesn't add role

I am using pycord for this so I can use slash commands.
Here is my code:
import discord, os
from dotenv import load_dotenv
from discord.ext import commands
load_dotenv(f'{os.getcwd()}/token.env')
bot = commands.Bot()
token = str(os.getenv('TOKEN'))
#bot.slash_command(description = 'mutes member of choice')
#commands.has_permissions(administrator = True)
async def mute(ctx, member: discord.Member):
guild = ctx.guild
mutedRole = discord.utils.get(guild.roles, name="Muted")
if not mutedRole:
mutedRole = await guild.create_role(name="Muted")
for channel in guild.channels:
await channel.set_permissions(mutedRole, speak=False, send_messages=False, read_message_history=True, read_messages=False)
await member.add_roles(mutedRole)
await ctx.send(f"Muted {member.mention}")
#mute.error
async def permserror(ctx, error):
if isinstance(error, commands.MissingPermissions):
ctx.respond('Sorry! You dont have permission.')
#bot.event
async def on_ready():
print(f'Client ready as {bot.user}')
bot.run(token)
This isn't my full code, but the other commands don't seem necessary for my problem.
Anyway, when I try to use this command, it doesn't throw an error in the console, but the application doesn't respond and it doesn't add the role.
I put a print statement between each line of code, and it seems to stop just before it adds the role.
How can I fix this?
Update: My previous code did not run so I have updated it.
This doesn't actually have to do with the code of the program. All you have to do is move the bot role to the top and it'll work. The error is 403 Forbidden (error code: 50013): Missing Permissions. Also, you have to reinvite the bot and add applications.commands if you haven't already.

Message in a specific Discord channel

Hi guys i'm trying to make the bot send a message automatically in a specific channel. I took the channel ID and pass it in the if condition (a_string.find ('data: []')! = -1). However this code gives me this error. See OUTPU ERROR.
P.S. I'm using Replit and Live is the file name (Live.py)
from discord.ext import commands
from Naked.toolshed.shell import execute_js, muterun_js
import sys
class Live(commands.Cog):
def __init__(self,client):
self.client=client
#commands.Cog.listener()
async def on_ready(self):
channel = self.get_channel(828711580434169858)
response = muterun_js('serverJs.js')
original_stdout = sys.stdout # Save a reference to the original standard output
if response.exitcode == 0:
a_string= str(response.stdout)#stampa in console
if (a_string.find('data: []') != -1):
print("Streamer: Offline ")
else:
print("Streamer: Online")
await channel.send('Live Link: https://...link....')
else:
sys.stderr.write(response.stderr)
#commands.command()
async def Live(self,ctx):
await ctx.send('')
def setup(client):
client.add_cog(Live(client))
OUTPUT ERROR:
Ignoring exception in on_ready
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "/home/runner/Solaris-IA/cogs/Live.py", line 12, in on_ready
channel = self.get_channel(828711580434169858)
AttributeError: 'Live' object has no attribute 'get_channel'
It's self.client.get_channel, not self.get_channel, you haven't defined that function
channel = self.client.get_channel(828711580434169858)

Simple bot command is not working in discord.py

I want to know in which text channels admin want to enable my bot functions. But in this case my code is not working.
The main idea was when admin typing !enable in text-chat, bot reacts to it and add text-chat id, guild id(ctx.channel.id) to the list, then bot responds in chat with bot has been enabled.
code where this command is not working:
channel = []
#bot.command()
async def enable(ctx):
global channel
print("Debug")
await ctx.send('Restriction bot has been enabled for this text channel.')
channel.append(ctx.channel.id)
full bot code:
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='!')
#bot.event
async def on_ready():
print(f'We have logged in as {bot.user.name}.')
channel = []
#bot.command()
async def enable(ctx):
global channel
print("Debug")
await ctx.send('Restriction bot has been enabled for this text channel.')
channel.append(ctx.channel.id)
#bot.event
async def on_message(ctx):
if ctx.author == bot.user:
return
#if ctx.channel.id != [for channnels in channel]:
# return
if ctx.attachments[0].height:
await ctx.author.send('Your media file is restricted!')
await ctx.delete()
The channel variable is initialized in your program so each time you will restart your bot, it will be emptied. One way you can solve your problem is by storing them in a file. The easiest way to do it would be to use the json library. You'll need to create a channels.json file.
The code :
from json import loads, dumps
def get_data():
with open('channels.json', 'r') as file:
return loads(file.read())
def set_data(chan):
with open('channels.json', 'w') as file:
file.write(dumps(chan, indent=2))
#bot.command()
async def enable(ctx):
channels = get_data()
channels.append(ctx.channel.id)
set_data(channels)
await ctx.send('Restriction bot has been enabled for this text channel.')
The channels.json file :
[]

Discord.py - passing an argument role functions

I wanted to create a command, like !iknow #user . A normal verification bot I think. Here's my code, I only pasted the important parts:
import discord
from discord.ext import commands
#client.command(pass_context=True)
async def iknow(ctx, arg):
await ctx.send(arg)
unknownrole = discord.utils.get(ctx.guild.roles, name = "Unknown")
await client.remove_roles(arg, unknownrole)
knownrole = discord.utils.get(ctx.guild.roles, name = "Verified")
await client.add_roles(arg, knownrole)
(The Unknown role is automatically passed when a user joins the server.)
The problem is: I get an error on line 6 (and I think I will get on line 9, too).
File
"/home/archit/.local/lib/python3.7/site-packages/discord/ext/commands/core.py",
line 83, in wrapped
ret = await coro(*args, **kwargs) File "mainbot.py", line 6, in iknow
await client.remove_roles(arg, unknownrole) AttributeError: 'Bot' object has no attribute 'remove_roles'
I just started learning python, so please don't bully me!
You're looking for Member.remove_roles and Member.add_roles.
You can also specify that arg must be of type discord.Member, which will automatically resolve your mention into the proper Member object.
Side note, it's no longer needed to specify pass_context=True when creating commands. This is done automatically, and context is always the first variable in the command coroutine.
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='!')
#client.command()
async def iknow(ctx, arg: discord.Member):
await ctx.send(arg)
unknownrole = discord.utils.get(ctx.guild.roles, name="Unknown")
await arg.remove_roles(unknownrole)
knownrole = discord.utils.get(ctx.guild.roles, name="Verified")
await arg.add_roles(knownrole)
client.run('token')

How can I get the contents of the last message sent on a discord server

I'm trying to set up a discord bot where it basically repeats what a user says under certain conditions. For the sake of simplicity, the conditions don't matter in the question. My current strategy is to get the logs when the condition is met and then repeat them. However, my code isn't working. I'm using python 3.6.4 (I haven't set up the repeat yet, I just want to get the last message sent.)
Here is my code:
import discord
TOKEN = 'XXXXXXXX'
client = discord.Client()
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('I am'):
msg = 'Hi {0.author.mention}'.format(message)
await client.send_message(message.channel, msg)
if message.content.startswith('Logs'):
logs= logs_from(general, limit=1)
print(logs)
#client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
client.run(TOKEN)
The issue is at
logs=logs_from(general, limit=1)
Here is the error
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/client.py", line 307, in _run_event
yield from getattr(self, event)(*args, **kwargs)
File "dadbot.py", line 17, in on_message
logs= logs_from(general, limit=1)
NameError: name 'logs_from' is not defined
Keep in mind this is my first discord bot and I'm struggling to find helpful info online.
The function logs_from is never defined, so you get the error.
Probably you mean:
logs = client.logs_from(general, limit=1)
so, you want the method log_from, from the client class.

Resources