Discord.py Image Posting - python-3.x

I'm trying to make a bot that posts a random image (for this example lets say bread) from google images. Right now I'm stuck with trying to post the image to Discord.
Here is the code:
import discord
import io
import aiohttp
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('/bread'):
#await message.channel.send('bread!')
async with aiohttp.ClientSession() as session:
async with session.get("https://www.google.com/search?q=bread&tbm=isch") as resp:
if resp.status != 200:
return await message.channel.send('Could not download file...')
data = io.BytesIO(await resp.read())
await message.channel.send(file=discord.File(data, 'image.png'))
client.run('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
Whenever I run the /bread command, I run into the could not download file error.
I don't want to download the image, I just want it posted to discord. I tried selecting a specific image URL, it too did not work.

About picture:
You can go at igmur.com and create own link to picture. You just have to drag picture to the site.(this pictures works at discord)
And that's my script for posting URL by bot
import random
Import discord
import http.client
from discord.ext import commands
Import aiohttp
#bot.command()
async def /bread(ctx):
messages = ["url", "bread2url", "bread3url"]
await ctx.send(random.choice(messages))

Related

Discord.py not responding to #client.event commands

I am not getting a "ping" response with this code. It was working before, but I am not sure what changed. There are no errors on my end, just no response.
Any feedback is appreciated.
import os
import random
import discord
from dotenv import load_dotenv
from discord.ext import commands
load_dotenv()
PREFIX = os.getenv("PREFIX")
TOKEN = os.getenv("TOKEN")
intents = discord.Intents().all()
bot = commands.Bot(command_prefix=PREFIX, intents=intents)
#bot.event
async def on_message(message):
if message.author == bot.user: # tells the bot not to respond to itself
return
#bot.event # ping-with-latency
async def on_message(message):
if message.content.startswith(PREFIX + 'ping'):
await message.channel.send(f'pong! {bot.latency}ms')
#bot.event
async def on_ready(): # display if online/ready
print("Bot is ready and logged in as {0.user}!".format(bot))
# run bot on server
bot.run(TOKEN)
I have checked all permissions and privileged gateway intents. I know I could be using client.command, but that also doesnt work.
You're defining two different callbacks for these events - this is probably the problem. Just put the author check in the main on_message.
#bot.event
async def on_message(message):
if message.author == bot.user: # tells the bot not to respond to itself
return
if message.content.startswith(PREFIX + 'ping'):
await message.channel.send(f'pong! {bot.latency}ms')

How do i make a discord bot receive text after a command

I want to become a fake discord bot, so i can use: !!send or something like that.
I have the token ready and i tried some repl.it templates but i have no idea of what to do.
here is the code i tried:
import discord
import os
import time
import discord.ext
from discord.utils import get
from discord.ext import commands, tasks
from discord.ext.commands import has_permissions, CheckFailure, check
os.environ["TOKEN"] = "no-token-for-you-to-see-here"
#^ basic imports for other features of discord.py and python ^
client = discord.Client()
client = commands.Bot(command_prefix = '!!') #put your own prefix here
#client.event
async def on_ready():
print("bot online") #will print "bot online" in the console when the bot is online
#client.command(pass_context=True)
async def send(ctx,*,message):
await client.say(message)
client.run(os.getenv("TOKEN")) #get your bot token and create a key named `TOKEN` to the secrets panel then paste your bot token as the value.
#to keep your bot from shutting down use https://uptimerobot.com then create a https:// monitor and put the link to the website that appewars when you run this repl in the monitor and it will keep your bot alive by pinging the flask server
#enjoy!
It was online, but the command didn't work.
The command send should be
#client.command()
async def send(ctx, *, message: str):
await ctx.send(message)
Also, you're defining two client(s). You need only one.
client = commands.Bot(command_prefix = '!!')
You're also importing some useless modules that you don't need right now.
Your final code should look like this:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix="!!")
#client.event
async def on_ready():
print("The bot is online")
#client.command()
async def send(ctx, *, message: str):
await ctx.send(message)
client.run("token-of-the-bot")
Please tell me if it works or not. Have a great day :)

How to make a python discord bot send a live GIF

I'm trying to get my basic discord bot to display a GIF using python as if a user was sending it from tenor.
I.E: example gif
I managed to get my bot to send a gif file that can be opened and viewed but I want to take it a step further and have it show the gif in chat.
Example
import discord
import io
import aiohttp
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 == 'hello':
embed = discord.Embed(title="Title", description="Desc", color=0x00ff00) #creates embed
file = discord.File("toodamnbad.gif", filename="image.png")
embed.set_image(url="attachment://image.png")
await message.channel.send(file=file)
client.run('TOKEN')
import discord
from discord.ext import commands
from discord.ext.commands import Bot
import json
import random
bot = commands.Bot(command_prefix="!", case_insensitive=True)
bot.remove_command('help')
#bot.event
async def on_ready():
print("Asuna")
#bot.command(case_insensitive=True)
async def command(ctx, member: discord.Member): # which command it responds to.
image = random.choice(["url", "url", "url"])
embed = discord.Embed(color = 0x303136, description = "text")
embed.set_image(url=image)
await ctx.send(embed=embed)
random gif↑
1 gif ↓
import discord
from discord.ext import commands
from discord.ext.commands import Bot
import json
bot = commands.Bot(command_prefix="!", case_insensitive=True)
bot.remove_command('help')
#bot.event
async def on_ready():
print("Asuna")
#bot.command(pass_context=True)
async def reactions(cxt):
embed = discord.Embed(color = 0x303136, description = "text")
embed.set_image(url='url')
await cxt.send(embed = embed)

discord.py send pm on member join

I'm trying to write a bot that sends a user a pm when he joins the server.
I searched and I found that to d this you need to have intents enabled, but when I enable them it gives me an error "RuntimeError: Event loop is closed". I can't figure out what exactly not working, I've seen somewhere that regenerate the bot token helps but it didn't help for me.
this is the code:
import discord
from discord.ext import commands
from dotenv import load_dotenv
from pathlib import Path
import os
# Load token
env_path = os.path.join(Path('.'), '.env')
load_dotenv(dotenv_path=env_path)
TOKEN = os.environ.get('DISCORD_TOKEN')
intents = discord.Intents(members=True)
bot = commands.Bot(command_prefix='.', intents=intents)
#bot.event
async def on_ready():
print('Bot is running...')
print(f"Name: {bot.user.name}")
print(f"ID: {bot.user.id}")
print('------')
#bot.event
async def on_member_join(member):
welcome_msg = f"hi {member}"
await member.send(welcome_msg)
bot.run(TOKEN)
I see that you are trying to DM the user as soon as they join a server, you should did {member} and the argument "member" is just a guild version of The user, and to display the name with member.name there for it will show the Member's name on the message.
Here is your Fixed Code:
import discord
from discord.ext import commands, tasks # add tasks if you're going to do tasks.
from dotenv import load_dotenv
from pathlib import Path
import os
# Load token
env_path = os.path.join(Path('.'), '.env')
load_dotenv(dotenv_path=env_path)
TOKEN = os.environ.get('DISCORD_TOKEN')
intents = discord.Intents(members=True)
bot = commands.Bot(command_prefix='.', intents=intents)
#bot.event
async def on_ready():
print('Bot is running...')
print(f"Name: {bot.user.name}")
print(f"ID: {bot.user.id}")
print('------')
#bot.event
async def on_member_join(member):
welcome_msg = f"hi {member.name}" # You don't need to define the message.
await member.send(welcome_msg) # You can do await member.send("message") instead of defining it.
bot.run(TOKEN)
Hope this helped. Have a nice day!

Keeeping the loop going until input (discord.py)

I'm running a discord.py bot and I want to be able to send messages through the IDLE console. How can I do this without stopping the bot's other actions? I've checked out asyncio and found no way through.
I'm looking for something like this:
async def some_command():
#actions
if input is given to the console:
#another action
I've already tried pygame with no results but I can also try any other suggestions with pygame.
You can use aioconsole. You can then create a background task that asynchronously waits for input from console.
Example for async version:
from discord.ext import commands
import aioconsole
client = commands.Bot(command_prefix='!')
#client.command()
async def ping():
await client.say('Pong')
async def background_task():
await client.wait_until_ready()
channel = client.get_channel('123456') # channel ID to send goes here
while not client.is_closed:
console_input = await aioconsole.ainput("Input to send to channel: ")
await client.send_message(channel, console_input)
client.loop.create_task(background_task())
client.run('token')
Example for rewrite version:
from discord.ext import commands
import aioconsole
client = commands.Bot(command_prefix='!')
#client.command()
async def ping(ctx):
await ctx.send('Pong')
async def background_task():
await client.wait_until_ready()
channel = client.get_channel(123456) # channel ID to send goes here
while not client.is_closed():
console_input = await aioconsole.ainput("Input to send to channel: ")
await channel.send(console_input)
client.loop.create_task(background_task())
client.run('token')

Resources