I am making a bot in discord.py and have made a meme command using AIOHTTP. I want the embed title to be the link to the meme and the footer should show the upvotes and all that stuff like in the screenshot.
Here is the code
#client.command(aliases=['memes'])
async def meme(ctx):
embed = discord.Embed(title='Meme', description=None)
async with aiohttp.ClientSession() as cs:
async with cs.get('https://www.reddit.com/r/wholesomememes/new.json?sort=hot') as r:
res = await r.json()
embed.set_image(url=res['data']['children'] [random.randint(0, 25)]['data']['url'])
await ctx.send(embed=embed, content=None)
```
replace it with this code
Toutorial
step 1: install praw (pip install praw)
step 2: go to https://www.reddit.com/prefs/apps create app
step 3: copy client_id and client_secret
step 4:run bot
#bot.command()
async def meme(ctx):
reddit = praw.Reddit(client_id='clientidhere',
client_secret='clientsecret',
user_agent='python')
memes = reddit.subreddit("memes").random()
await ctx.send(memes.url)
Related
Getting Error When Using Custom Emojis In Discord.py
import discord
from discord.ext import commands
client = commands.Bot(intents=intents,command_prefix="$")
#client.event
async def on_message(msg):
if msg.author == client.user:
return
else:
await msg.channel.send("<:doory_fruit:1062084428228206657>")
client.run("MyToken")
error 1 when not inputting the id:
Image Link
error 2 when using name and id :
Image 2 Link
Any Help
I'm making a slash command that can send dms to a specific user id that's been determined by a command argument. It works for specific user ids, but not all of them, including mine my alt account. Is it some permission thing or is the user id out of range?
My code
import discord
from discord.ext import commands
import os
from dotenv import load_dotenv
# importing environmental vars
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
GUILD = os.getenv("DISCORD_GUILD")
APP_ID = os.getenv("APP_ID")
PUB_KEY = os.getenv("PUBLIC_KEY")
GUILD_ID = os.getenv("GUILD_ID")
GENERAL_CHAN_ID = os.getenv("CHANNEL_GENERAL_ID")
#finished importing .env vars
intents = discord.Intents.all()
activity = discord.Activity(name="being awesome losers", type = discord.ActivityType.streaming)
bot = discord.Bot(intents=intents, activity=activity)
#bot.event
async def on_ready():
print(f"We have logged in as {bot.user}")
#bot.slash_command(description="sends message to someone still testing",guild_ids=[GUILD_ID])
async def send_message(ctx, user_id: str, message: str):
user = bot.get_user(int(user_id))
await user.send(message)
await ctx.respond("Message sent successfully!", ephemeral = True)
#bot.event
async def on_message(message):
channel = bot.get_channel(956302622170701946)
if message.content.startswith("help"):
await message.author.send('👋')
bot.run(TOKEN)
When I input an ID that doesn't work it gives me this traceback
AttributeError: 'NoneType' object has no attribute 'send'
Traceback (most recent call last):
File "C:\Users\Rayan\source\repos\DBot\DiscordBot\lib\site-packages\discord\commands\core.py", line 124, in wrapped
ret = await coro(arg)
File "C:\Users\Rayan\source\repos\DBot\DiscordBot\lib\site-packages\discord\commands\core.py", line 980, in _invoke
await self.callback(ctx, **kwargs)
File "c:\Users\Rayan\source\repos\DBot\main.py", line 56, in send_message
await user.send(message)
AttributeError: 'NoneType' object has no attribute 'send'
Help is greatly appreciated! Thank you!
I do not think the issue is that the ID is out of range. It's simply that the user is not in the cache.
import discord
from discord.ext import commands
import os
from dotenv import load_dotenv
# importing environmental vars
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
GUILD = os.getenv("DISCORD_GUILD")
APP_ID = os.getenv("APP_ID")
PUB_KEY = os.getenv("PUBLIC_KEY")
GUILD_ID = os.getenv("GUILD_ID")
GENERAL_CHAN_ID = os.getenv("CHANNEL_GENERAL_ID")
#finished importing .env vars
intents = discord.Intents.all()
activity = discord.Activity(name="being awesome losers", type = discord.ActivityType.streaming)
bot = discord.Bot(intents=intents, activity=activity)
#bot.event
async def on_ready():
print(f"We have logged in as {bot.user}")
#bot.slash_command(description="sends message to someone still testing",guild_ids=[GUILD_ID])
async def send_message(ctx, user_id: str, message: str):
user = await bot.fetch_user(int(user_id))
await user.send(message)
await ctx.respond("Message sent successfully!", ephemeral = True)
#bot.event
async def on_message(message):
channel = bot.get_channel(956302622170701946)
if message.content.startswith("help"):
await message.author.send('👋')
bot.run(TOKEN)
This will always fetch the user and therefore will be able to DM everyone, even not in the cache.
The buttons work after the command is sent, they show up on the embed, but once the bot restarts and I press the button that was on the previous embed, the discord app gives me an error that says interaction failed, here's the discord.py code.
async def ticket(ctx, *title):
button = Button(label="Ready to start buying?",
style=discord.ButtonStyle.green)
guild = ctx.guild
dropperrole = discord.utils.get(guild.roles, id=1003171723207774218)
topdropperrole = discord.utils.get(guild.roles, id=1004989656137465917)
title = list(title)
title = " ".join(map(str, title))
view = View()
view.add_item(button)
async def button_callback(interaction):
await interaction.response.send_message("Creating channel...",
ephemeral=True)
await asyncio.sleep(3)
await interaction.edit_original_message(
content=
f"Channel successfully created #ticket-{(interaction.user.name).lower()} !"
)
overwrites = {
guild.default_role:
discord.PermissionOverwrite(view_channel=False),
interaction.user: discord.PermissionOverwrite(view_channel=True),
guild.me: discord.PermissionOverwrite(view_channel=True),
dropperrole: discord.PermissionOverwrite(view_channel=True),
topdropperrole: discord.PermissionOverwrite(view_channel=True)
}
chan = await ticket_category.create_text_channel(
f"ticket-{(interaction.user.name).lower()}", overwrites=overwrites)
id = discord.utils.get(
ctx.guild.channels,
name=f"ticket-{(interaction.user.name).lower()}")
await interaction.edit_original_message(
content=f"Channel successfully created {id.mention}!")
ccEmbed = discord.Embed(title=f"Hello {interaction.user.name}!",
color=0x2ecc71)
ccEmbed.add_field(
name="Ready to buy?",
value="Type `$dhc` to buy DHC, or `$buygen` to buy Gen! type `$fastpass` to buy fastpass, this allows you to skip all orders! To view prices, type `$prices`!",
inline=True)
ccEmbed.set_footer(text="discord.gg/dhcc | Rvse's Gen")
await chan.send(embed=ccEmbed)
button.callback = button_callback
You need to setup persistence so the bot will restart the view of your button when it launches. I think your are using Rapptz discord library? If so here is an example you can checkout:
https://github.com/Rapptz/discord.py/blob/master/examples/views/persistent.py
I am trying to put a cursed image command in my discord.js bot but it keeps coming up with this error
got('https://www.reddit.com/r/madlads/random/.json').then(response => {
^
ReferenceError: got is not defined
Here is the code
if(command === "cursed") {
got('https://www.reddit.com/r/cursedimages/random/.json').then(response => {
let content = JSON.parse(response.body);
var image = content[0].data.children[0].data.url;
let permalink = content[0].data.children[0].data.permalink;
let memeUrl = `https://reddit.com${permalink}`;
let memeImage = content[0].data.children[0].data.url;
let memeTitle = content[0].data.children[0].data.title;
let memeUpvotes = content[0].data.children[0].data.ups;
let memeNumComments = content[0].data.children[0].data.num_comments;
const cursedembed = new Discord.MessageEmbed()
.setColor('RANDOM')
.setTitle(content[0].data.children[0].data.title)
.setURL(`${memeUrl}`)
.setImage(image)
.setFooter(`👍 ${memeUpvotes} 💬 ${memeNumComments}`)
.setTimestamp()
message.channel.send(cursedembed);
});
}
Since you don't have node-fetch as one of your packages, you won't be able to use the fetch function. In order to use this package, you'll have to follow three steps.
Install node-fetch. This can be done by running npm i node-fetch in your project directory.
Import node-fetch into your code. This can be done by having const fetch = require('node-fetch'); at the top of your code file, similar to your discord.js import.
Replace got with fetch.
After that, you should be able to use fetch in order to download web content and post reddit content on discord.
import discord
from discord.ext import commands
import platform
import random
import time
bot = commands.Bot(command_prefix='+', case_insensitive=True)
#bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}(ID: +{bot.user.id}) |'
f'Connected to {str(len(bot.guilds))} servers |'
f'Connected to {str(len(set(bot.get_all_members())))} users')
print('--------')
print('CREATED AND HOSTED BY Fataldagod | Fixed Version')
#bot.event
async def on_command_error(ctx, error):
# Ignore these errors:
ignored = (
commands.CommandNotFound, commands.UserInputError, commands.BotMissingPermissions,
commands.MissingPermissions, discord.errors.Forbidden, commands.CommandInvokeError,
commands.MissingRequiredArgument)
if isinstance(error, ignored):
return
#bot.command(pass_context=True)
#commands.has_permissions(kick_members=True)
async def userinfo(ctx, user: discord.Member):
try:
embed = discord.Embed(title="{}'s info".format(user.name),
description="Here's what I could find.",
color=discord.Colour.dark_red())
embed.add_field(name="Name", value=user.name, inline=True)
embed.add_field(name="ID", value=user.id, inline=True)
embed.add_field(name="Status", value=user.status, inline=True)
embed.add_field(name="Highest role", value=user.top_role)
embed.add_field(name="Joined", value=user.joined_at)
embed.set_thumbnail(url=user.avatar_url)
await ctx.send(embed=embed)
except:
await ctx.send("Missing Requrired Args")
#commands.has_permissions(administrator=True)
#bot.command(pass_context=True)
async def send(ctx, *, content: str):
for member in ctx.guild.members:
c = await member.create_dm()
try:
await c.send(content)
await ctx.send("MassDM message sent to: {} ".format(member))
except Exception:
await ctx.send("MassDM message blocked by: {} ".format(member))
Was wondering what I can change to make it so the bot DMs specific roles rather than the entire server?
For example instead of me typing +send (message) I'd like to type +send #role1 #role2 role3 #role4 (message) or something along these lines.
Any help is much appreciated.