marsey_bot/marsey_bot.py

91 lines
3.0 KiB
Python

#!/usr/bin/env python
# encoding: utf-8
import os
import discord
from discord.ext import commands
from discord.ext import tasks
from PIL import Image, ImageSequence
import string
def wheres_marsey(message_text): #returns list of potential marsey names
marsey_names = []
message_text = message_text.lower().split('!') #convert message to all lowercase and checks for "!"
for marsey_name in message_text:
marsey_name = marsey_name.translate(str.maketrans('', '', string.punctuation)) #strip punctuation
marsey_name = marsey_name.split(' ')
marsey_names.append(marsey_name[0]) #only look for first word afer "!"
return [x for x in marsey_names[1:] if x] #ignore empty strings
def is_animated(file_path): #check if webp is animated or static
try:
media = Image.open(file_path)
Index = 0
for Frame in ImageSequence.Iterator(media): #check number of frames
Index += 1
if Index > 1: #if more than one frame return True
return True
else:
return False
except:
return False
def webp2gif(abs_media_path): #convert webp to gif
media = Image.open(abs_media_path) #path of webp file
media.info.pop('background', None)
abs_media_path = abs_media_path[:-4]+'gif' #change the path from webp to gif
media.save(abs_media_path, 'gif', optimize=False, save_all=True, disposal=2) #temp save a gif file (there might be a better way but i lazy :marseyteehee:)
return abs_media_path #return gif path
client = commands.Bot(command_prefix = '!')
@client.event #print ready in command line to verify bot initiation
async def on_ready():
print('ready')
@client.event
async def on_message(message): #bot reads every message in server
message_text = message.content
marsey_names = wheres_marsey(message_text) #make list of called marseys
marsey_queue = [] #empty list of marseys to send
for marsey_name in marsey_names:
#find directory of marsey
bot_dir = os.path.dirname(__file__)
rel_marsey_path = "emojis/"+marsey_name+".webp"
abs_marsey_path = os.path.join(bot_dir, rel_marsey_path)
flag = 0 #flag used in webp to gif file conversion
if os.path.isfile(abs_marsey_path): #only continue if marsey exists
#if marsey is animated, turn it into a gif
if is_animated(abs_marsey_path) is True:
abs_marsey_path = webp2gif(abs_marsey_path)
flag = 1 #flag for deleting temp gif file after sent
#open file and add it to send queue
with open(abs_marsey_path, 'rb') as f:
marsey_queue.append(discord.File(f))
#delete temp file
if flag == 1:
os.remove(abs_marsey_path)
flag = 0 #reset flag
if marsey_queue: #only send marsey(s)
await message.channel.send(files=marsey_queue)
#token
with open('discord_token.txt') as f:
discord_token = f.readline()
client.run(discord_token)