I've been working on a discord bot which will take any image posted and automatically face swap that image with mrbeast But i cant seem to figure out how to take the output from the face swapper api and turn that into an image that the bot can post
I've tried using guh.channel.send(file = theimage)
which returned a very long error.
And I've tried saving the image to my device but the script lacked permissions and I don't want to do this as I don't want to have hundreds of my beast face swap images saved to my device.
previously when I had print("response.content") in place of sending a discord message it output a super long string of letters and numbers separated by slashes
import discord
import requests
import base64
from PIL import Image
from io import BytesIO
intents = discord.Intents.all()
api_key = "**********"
url = "https://api.segmind.com/v1/faceswap-v2"
def image_file_to_base64(image_path):
with open(image_path, 'rb') as f:
image_data = f.read()
return base64.b64encode(image_data).decode('utf-8')
def image_url_to_base64(image_url):
response = requests.get(image_url)
image_data = response.content
return base64.b64encode(image_data).decode('utf-8')
class Client(discord.Client):
async def on_message(self, guh):
if guh.author.bot:
return
try:
image = guh.attachments[0].url
data = {
"source_img": image_file_to_base64(r"C:\Users\ajoes\Downloads\discord bot\MrBeast.jpg"),
"target_img": image_url_to_base64(image),
"source_faces_index": 0,
"face_restore": "codeformer-v0.1.0.pth",
"base64": False
}
headers = {'x-api-key': api_key}
response = requests.post(url, json=data, headers=headers)
theimage = Image.open(BytesIO(response.content))
await guh.channel.send(theimage)
except IndexError:
return
client = Client(intents=intents)
client.run("TOKEN")
In it's current state when I send an image the bot simply replies with
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=803x920 at 0x239294F5DF0\>
If you want to send an image to Discord, you need to use the data class discord.File
:
class Client(discord.Client):
async def on_message(self, guh):
if guh.author.bot:
return
try:
image = guh.attachments[0].url
data = {
"source_img": image_file_to_base64(r"C:\Users\ajoes\Downloads\discord bot\MrBeast.jpg"),
"target_img": image_url_to_base64(image),
"source_faces_index": 0,
"face_restore": "codeformer-v0.1.0.pth",
"base64": False
}
headers = {'x-api-key': api_key}
response = requests.post(url, json=data, headers=headers)
bytes_img = BytesIO(response.content)
file = discord.File(fp=bytes_img, filename='MrBeast.jpg')
await guh.channel.send(file=file)
except IndexError:
return