I am trying to replace the avatar image of the bot when a user runs a command. How would I do this? I have managed to replace the nickname but not the image.
await ctx.guild.me.edit(nick=nick)
^ Replaces the nickname.
I tried (nick=nick, avatar=avatar) but it did not work.
EDIT:
#client.command()
async def test(ctx):
if ctx.guild.id == second_server:
await ctx.guild.me.edit(nick=nick, avatar_url=avatar)
pfp_path = "Profile-Picture.png"
with open(pfp_path, "rb") as pfp:
await client.user.edit(password=None, avatar=pfp.read())
print("profile picture changed")
According to the official docs, the following should work:
import discord
client = discord.Client()
token = '...'
#client.event
async def on_ready():
pfp_path = "file.jpg"
with open(pfp_path, "rb") as pfp:
await client.user.edit(password=None, avatar=pfp.read())
print("profile picture changed")
client.run(token)
You cannot directly give a URL to the desired profile picture.
Note: the only formats supported are JPEG and PNG
Related
I am trying to access the content of a message and print it using discord.py. The problem is, that the content is allways empty no matter what. The code works on my laptop but just refuses to work on this pc. The same has already happened when trying to run other, more complex, codes that worked on other devices. There are no errors showing up.
import nest_asyncio
nest_asyncio.apply()
import discord
TOKEN = "TOKEN"
client = discord.Client(intents=discord.Intents.default())
#client.event
async def on_ready():
print("logged in as {0.user}".format(client))
#client.event
async def on_message(message):
username = str(message.author).split("#")[0]
user_message = message.content
channel = str(message.channel.name)
print(f"{username}: {user_message} ({channel})")
client.run(TOKEN)
You need to enable the Guild Message Intent: https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guild_messages
Im trying to make a verify command where it sends me a dm, and I can check wether they are verified or not, here is my code:
import discord
from discord.ext import commands, tasks
from itertools import cycle
import os
import time
import json
token = os.environ['token']
def get_prefix(client, message):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
return prefixes[str(message.guild.id)]
client = commands.Bot(command_prefix=get_prefix)
#client.event
async def on_ready():
print('Bot is ready')
await client.change_presence(activity=discord.Game(f'My prefix is {get_prefix}'))
#client.command()
async def verify(ctx, message, jj=discord.Member.get_user("270397954773352469")):
person = message.author
jj.create_dm()
await ctx.send('Awaiting Verification, you will recieve a dm when you are verified')
await jj.send(f'{person} is trying to be verified, do you know him/her?')
You don't have to use parameter message use ctx which you already have to get ctx.author. You can get a user by id only with client.get_user or client.fetch_user (and use it inside a function, not as a parameter). Last thing - you usually don't have to use create_dm(), but if you want to you can, but remember to correct it to await jj.create_dm().
#client.command()
async def verify(ctx):
jj = await client.fetch_user(270397954773352469)
person = ctx.author
await ctx.send('Awaiting Verification, you will recieve a dm when you are verified.')
await jj.send(f'{person.mention} is trying to be verified, do you know him/her?')
If you have something like verified role (you won't get a message if someone is verified):
#client.command()
async def verify(ctx):
role = discord.utils.get(ctx.guild.roles, name="verified") # name of your role
person = ctx.author
if role in person.roles:
await ctx.send('You are already verified!')
else:
jj = await client.fetch_user(270397954773352469)
await ctx.send('Awaiting Verification, you will recieve a dm when you are verified.')
await jj.send(f'{person.mention} is trying to be verified, do you know him/her?')
i have only started to look around and figure how things work with discord.py bot. Tried making a bot that welcomes people in a certain channel. But no matter what I do, it doesn't seem to be working. The code executes and the on_ready fires. But its not welcoming the user like its supposed to. Can someone help?
import discord
from discord.ext import commands
from discord.ext.commands import Bot
from discord import Color
import asyncio
import datetime
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
client=commands.Bot(command_prefix="-")
client.remove_command("help")
#client.event
async def on_ready():
print("Created by Goodboi")
print(client.user.name)
print("-----")
#client.event
async def on_member_join(member):
embed = discord.Embed(colour=0xe8744f,
description=f"Welcome to the discord server",)
embed.set_author(name=f"{member.mention}",icon_url=f"{member.avatar_url}")
embed.set_footer(text=f"{member.guild}",icon_url=f"{member.guild.icon_url}")
embed.timestamp = datetime.datetime.utcnow
channel = client.get_channel(id=) #usedid
await channel.send(embed=embed)
client.run('token') #usedtoken
Hi you have to get channel like this
#client.event
async def on_member_join(member):
embed = discord.Embed(colour=0xe8744f,
description=f"Welcome to the discord server",)
embed.set_author(name=f"{member.mention}",icon_url=f"{member.avatar_url}")
embed.set_footer(text=f"{member.guild}",icon_url=f"{member.guild.icon_url}")
embed.timestamp = datetime.datetime.utcnow()
channel = member.guild.get_channel(channel_id) #usedid
await channel.send(embed=embed)
The only thing you did wrong is passing no brackets to your datetime.datetime.utcnow "function" which gives out the following error:
TypeError: Expected datetime.datetime or Embed.Empty received builtin_function_or_method instead
If you put brackets behind the definition of your timestamp it should work:
#client.event
async def on_member_join(member):
embed = discord.Embed(colour=0xe8744f,
description=f"Welcome to the discord server", )
embed.set_author(name=f"{member.mention}", icon_url=f"{member.avatar_url}")
embed.set_footer(text=f"{member.guild}", icon_url=f"{member.guild.icon_url}")
embed.timestamp = datetime.datetime.utcnow() # Added brackets
channel = client.get_channel(ChannelID) # No "id=" needed
await channel.send(embed=embed)
You can also have a look at the docs: https://docs.python.org/3/library/datetime.html#datetime.datetime
This should work for you, though, can be improved in many ways, but if you asked for this, then here is it.
#client.event
async def on_member_join(member) :
channel = client.get_channel(CHANNEL ID) # First we need to get the channel we want to post our welcome message.
embed = discord.Embed(
colour=0xe8744f ,
description='Welcome to the discord server' ,
timestamp=datetime.utcnow()
)
embed.set_author(name=f'{member.mention}' , icon_url=f'{member.avatar_url}')
embed.set_footer(text=f'{member.guild}' , icon_url=f'{member.guild.icon_url}')
await channel.send(embed=embed) #Send the embed
I'm trying to send embeds in discord.py, but whenever i run the code nothing gets sent. No errors nothing. Here is my code:
from variables.variables import client, token
import discord
#client.command()
async def test(ctx):
imageURL = "https://discordapp.com/assets/e4923594e694a21542a489471ecffa50.svg"
embed = discord.Embed()
embed.set_image(url=imageURL)
await ctx.send(embed=embed)
client.run(token)
This is what the embed looks like using above code:
Thanks!
.svg is not supported. Here's the same image in .png format:
#client.command()
async def test(ctx):
imageURL = "https://cdn.discordapp.com/attachments/744631318578462740/755866713182044240/ezgif-4-6eba1fde99f2.png"
embed = discord.Embed()
embed.set_image(url=imageURL)
await ctx.send(embed=embed)
I have this function here that uses the folder name as a command. Right now the only folders are "hug" and "headpat". So when I send .hug or .headpat to Discord it will go into that folder, grab a random image and post it.
#client.event
async def on_message(message):
async def random_image(dir): #picks a random image from local directory
if message.content.lower() ==f".{dir}":
image = random.choice(os.listdir(dir))
embed = discord.Embed(color = 0xff9e00)
chosen_one = discord.File(f"{dir}\\{image}", filename = image)
embed.set_image(url = f"attachment://{image}")
await message.channel.send (embed = embed, file = chosen_one)
print(f"{image} sent in response to {(message.author)}.")
print(f"----------")
However, I would like to be able to do something like as follows, but I am not sure where to start.
#bot.command()
async def folder_name(ctx):
#code that does the same as the function above
By default with the commands extension, the function's name is the command name. However, the #commands.command decorator have a aliases argument that you can use along with Context.invoked_with:
#bot.command(aliases=['hug', 'headpat'])
async def folder_name(ctx):
image = random.choice(os.listdir(ctx.invoked_with))
embed = discord.Embed(color = 0xff9e00)
chosen_one = discord.File(f"{dir}\\{image}", filename=image)
embed.set_image(url = f"attachment://{image}")
await ctx.send (embed = embed, file=chosen_one)
print(f"{image} sent in response to {ctx.author}.")
print(f"----------")
Note that if someone types !folder_name, the command will execute so you'll have to add a check like this:
if ctx.invoked_with == ctx.command.name:
#Do stuff
Here is a simple bot that implements your code as a command.
import discord
from discord.ext import commands
TOKEN = "your token"
PREFIXES = ['.']
bot = commands.Bot(command_prefix=PREFIXES)
#bot.command(name='image')
async def random_image(ctx, dir):
image = random.choice(os.listdir(dir))
embed = discord.Embed(color = 0xff9e00)
chosen_one = discord.File(f"{dir}\\{image}", filename = image)
embed.set_image(url = f"attachment://{image}")
await ctx.send (embed = embed, file = chosen_one)
print(f"{image} sent in response to {(message.author)}.")
print(f"----------")
#bot.event
async def on_ready():
print(f"Logged in as {bot.user.name} in {len(bot.guilds)} guilds!")
#bot.event
async def on_message(message):
if message.author.bot: # I always do this to make sure it isn't a bot
return
await bot.process_commands(message)
if __name__ == '__main__':
try:
bot.run(TOKEN)
finally:
print("Logging Out")
I'd actually recommend using links instead of files/folders for their unreliable and often produce problems and bugs in your code and they just don't work very well with discord.py.
Here's an example of your desired command.
import discord
from discord.ext import commands
from discord import Embed
import random
client = commands.Bot(command_prefix=".")
headpat_image_links = ['https://media.tenor.com/images/ad8357e58d35c1d63b570ab7e587f212/tenor.gif', 'https://image.myanimelist.net/ui/xUjg9eFRCjwANWb4t4P8QbyfbVhnxa2QGYxoE7Brq1sHDVak6YxhLP3ZbNkkHm6GX9x8FWB1tWCapNyEqSltXa8wxAdwIERdrHGhYPilHJ8']
secret_headpat = random.choice(headpat_image_links)
#client.command()
async def headpat(ctx):
e=Embed(title="Headpats!", description="whatever description you want")
e.set_image(url=secret_headpat)
await ctx.send(embed=e, content=None)
client.run('TOKEN')
I've checked it and it works like a charm ;)
It's the same concept for the hug command. Just choose a random link to embed :)
PS:
Make sure you don't use any imgur links, imgur's API and links has been on the fritz and no longer works with discord.py. Well, it no longer works with embedded messages. Just don't use it. :>