Send a screenshot to discord channels - python-3.x

I am writing a program that screenshots my computer screen and send it to my discord channel. This is done by a discord bot made by me. Below shows what I did:
First, define a function that does a screenshot:
import keyboard
import mouse
import os
def screenshot():
keyboard.press('win + shift + s')
time.sleep(1.5)
mouse.press('left')
mouse.drag(0, 0, 1600, 850, duration=0.2)
mouse.release('left')
filename = f"Screenshot_{time.strftime('%Y%m%d')}_{time.strftime('%I%M%S')}.png"
os.chdir('Path_of_screenshot_saves_here') # I have tested it, the path is correct
time.sleep(1)
with open(filename, 'r') as f:
return f
Then, the code of the discord bot:
import discord
import keyboard
import time
import os
import mouse
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
#client.event
async def on_ready():
print(f'Logged in as {client.user}')
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$ss'): # sends a screenshot when it receives a message starts with '$ss'
await message.channel.send(screenshot())
client.run('my_bot_token_here')
The bot does send something to the channel. However, instead of sending out a png file, it sends something like this:
<io.TextIOWrapper name='Screenshot_20230219_030537.png' mode='r' encoding='cp1252'>
What have I done wrong? Are there any ways to solve this? Thanks for any help in advance.

Related

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 Rewrite: Functions suddenly stopped working

I've been messing around with the discord bot python rewrite for the last few days. I've noticed that adding multiple functions tends to cause other functions to stop working. I added a looping task that sends a video from a random list of URLs and I initially thought that may be causing the other functions to stop working, but commenting that out still causes issues. It's pretty annoying when you have no error messages to go off of. Any help would be greatly appreciated!
import discord
from discord.ext import commands, tasks
import re
from random import randint
client = commands.Bot(command_prefix = "//")
#client.event
async def on_ready():
print("The bot is doing stuff.")
#client.event
async def on_message(message):
"""Deletes <specific> YT link"""
if <specific yt link> in message.content:
await message.delete()
print("video deleted")
#client.event
async def on_message(message):
"Sends a peeposalute whenever someone says 'goodnight'"
gn = re.compile('goodnight|good night|gn')
if gn.search(message.content.lower()):
await message.channel.send('<:peepoSalute:665687773407215637>')
print('peepo has saluted')
#client.event
async def on_message(message):
"""Checks the #new-uploads channel, reacts to any new messages and adds the video URL to the list"""
if message.channel.id == <channel id>:
with open('videos.txt', 'a') as f:
f.write(message.content + '\n')
print("New video added to list")
message.add_reaction('<:Wowee:592122719546638408>')
#tasks.loop(hours=24)
async def daily_video():
"""Sends a random video in #general daily"""
with open('videos.txt', 'r') as f:
videos = f.readlines()
target_general_id = <channel id>
general_id = client.get_channel(target_general_id)
await general_id.send(videos[randint(0, len(videos) - 1)])
print("Daily video sent")
#daily_video.before_loop
async def before():
await client.wait_until_ready()
print("Finished waiting")
daily_video.start()
client.run(<token>)

Discord.py Image Posting

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))

How should I Private DM my user after they send a command? (Discord Python)

I am coding a python discord program, and I'm very new to this. I tried a few answers to Private DMs, but none of them seemed to work. I can't tell if I am doing anything wrong. I would like any user/a user with a role to say a command, eg .gen and the bot sends dm.
My code:
import discord
import random
from discord.ext import commands
from random import randint
bot = commands.Bot(command_prefix='.', description='Generates accounts')
x=1
spotifynum = 0
spotifyvisnum = 1
with open("spotify.txt") as f:
spot = f.readlines()
spot = [x.strip() for x in spot]
with open("spotify.txt") as f:
spot = f.readlines()
spot = [x.strip() for x in spot]
#bot.event
async def on_ready():
print(("-")*40)
print('Logged in as')
print(bot.user.name)
print(("-")*40)
#bot.command()
async def hello():
await bot.say('Hello!')
#bot.command()
async def gen():
await ctx.author.send("hi")
bot.run('private_code')
You are looking at the docs for rewrite, but probably using async code. You need to use await bot.send(dest, message) to send messages in async

Resources