[PYTHON] Create a BOT that can call images registered with Discord like pictograms

At first(?)

It seems convenient to be able to put out an image immediately like a LINE stamp. I made it because I thought

Finished product

1 First, register the image キャプチャ.PNG

2 Enclose the name used when registering in! In the message to be sent. Then the image is sent. キャプチャ2.PNG

To delete the registered image, do s! Del [name]

program

#coding=utf-8
import discord
import re
import os
import glob

client = discord.Client()

@client.event
async def on_ready():
    print('Connected')

@client.event
async def on_message(message):
    if message.author.bot:
        return

    word = re.compile("s!add (.+)").search(message.content)
    if word:
        wo = word.group(1)
        await message.channel.send("setting up...")
        picu = message.attachments[0].url
        file = str(message.guild.id) + "/" + wo + ".txt"
        try:
            os.mkdir(f"./{str(message.guild.id)}")
        except FileExistsError:
            pass
        with open(file, mode='w') as f:
            f.write(str(picu))
        await message.channel.send("Added a stamp.")
        f.close()
        return

    wordd = re.compile("s!del (.+)").search(message.content)
    if wordd:
        woo = wordd.group(1)
        file = str(message.guild.id) + "/" + woo + ".txt"
        if (os.path.exists(file)):
            await message.channel.send("Deleting...")
            os.remove(file)
            await message.channel.send("The stamp has been deleted.")
        else:
            await message.channel.send("The stamp was not found.")
        return

    pe = re.compile('s!list (.+)').search(message.content)
    if pe:
        casfo = glob.glob(str(message.guild.id) + "/*")
        nopas = str(message.guild.id)
        lis = []
        for file in casfo:  #File list
            prii = file.lstrip(nopas)
            pri = prii.rstrip(".txt")
            pr = pri.rstrip("/")
            p = pr.lstrip("\\")
            lis.append(p)
        pa = int(pe.group(1))
        no = len(lis)
        embed = discord.Embed(title="Stamp list", description=f"{str(pa)}Page page\n Number of stamps:{len(lis)}", color=0x4682b4)
        c = 0
        cc = 0
        if pa > 1:
            ccc = pa*10
            c = ccc - 10
        while True:
            try:
                naiy = lis[c]
            except:
                if pa == 1:
                    await message.channel.send("There is no stamp yet.")
                    return
                await message.channel.send(f"{str(pa)}There is no page yet")
                return
            c = c + 1
            embed.add_field(name=str(c), value=naiy)
            if c == pa * 10:
                await message.channel.send(embed=embed)
                return
            if c == len(lis):
                break
        await message.channel.send(embed=embed)
        return

    s = message.content
    if s.count("!") == 2:
        x = s.find("!")
        y = s.find("!", x+2)
        sta = s[x + 1 : y]
        if sta == None:
            return
        pas = str(message.guild.id) + "/" + sta + ".txt"
        if os.path.exists(pas) == False:
            return
        with open(pas) as f:
            url = f.read()
        f.close()
        await message.channel.send(url)
        return

print('connecting...')
#Because it is TOKEN for test, it can be leaked
client.run("NzA2MzQwNTMwMDE5MjM3OTQ0.Xq405w.pwRREjj-8N4MKph3QcV9NGb5EIM")

It's very long because I don't have the vocabulary (?) Of the chords.

How it works

When registering images, create a folder with the server ID and Just create a text file with the URL of the image in it with the name of the image. What happens when you send a stamp If there are two !, check the text between the two !. Then read the text file with the name of the text between! In the folder with that server ID. Send the URL of the image in it. Complete

Explanation of the most important thing in this program ↑ this ↓ The one who examines the text between the two!

s = message.content #Because it's long, put it in s
if s.count("!") == 2:
    x = s.find("!")
    y = s.find("!", x+2)
    sta = s[x + 1 : y]
    if sta == None:
        return
    pas = str(message.guild.id) + "/" + sta + ".txt"
    if os.path.exists(pas) == False:
        return
    with open(pas) as f:
        url = f.read()
    f.close()
    await message.channel.send(url)
    return

In the message! The part to look up the two and the name surrounded by them.

How it works: 1 First, if s.count ("!") == 2:, check if there are two! 2 Find the number of first! And second! Locations with x = s.find ("1") and y = s.find ("!", X + 2). 3 Examine the characters in the area surrounded by! At sta = s [x + 1: y] 4 Make sure it's not empty with if sta == None: 5 pas = str(message.guild.id) + "/" + sta + ".txt" Is the path of the text file where the URL of the registered image is recorded 6 if os.path.exists(pas) == False: Check if the file with the path of 5 exists 7 with open(pas) as f: Read the contents of the text file with 5 paths and send it

At the end

I can't think of it the end

Recommended Posts

Create a BOT that can call images registered with Discord like pictograms
Create a web API that can deliver images with Django
Create a program that can generate your favorite images with Selenium
Make a Discord Bot that you can search for and paste images
Create a discord bot that notifies unilaterally with python (use only requests and json)
Create a bot that only returns the result of morphological analysis with MeCab on Discord
[LINE Messaging API] Create a BOT that connects with someone with Python
Create a bot that boosts Twitter trends
Create a web app that can be easily visualized with Plotly Dash
Create test data like that with Python (Part 1)
Create a bot with AWS Lambda that automatically starts / stops Instances with specific tags
Create a LINE BOT with Minette for Python
I registered PyQCheck, a library that can perform QuickCheck with Python, in PyPI.
Create a page that loads infinitely with python
You can easily create a GUI with Python
Steps to create a Twitter bot with python
Convert images from FlyCapture SDK to a form that can be used with openCV
Make a BOT that shortens the URL of Discord
Create a chatbot that supports free input with Word2Vec
Create a batch of images and inflate with ImageDataGenerator
Create a slack bot
A story that I had a hard time trying to create an "app that converts images like paintings" with the first web application
Create a web application that recognizes numbers with a neural network
Create a PythonBox that outputs with Random after PEPPER Input
I made a LINE BOT that returns parrots with Go
Create a function to display images like Jupyter / RStudio [Docker]
Create a machine learning app with ABEJA Platform + LINE Bot
Create a Mastodon bot with a function to automatically reply with Python
Let's create a script that registers with Ideone.com in Python.
Create a life game that is manually updated with tkinter
Create a Twitter BOT with the GoogleAppEngine SDK for Python
Tornado-Let's create a Web API that easily returns JSON with JSON
I made a plug-in that can "Daruma-san fell" with Minecraft
Let's make a diagram that can be clicked with IPython
Let's make a Discord Bot.
Create a homepage with django
Create a heatmap with pyqtgraph
I made a discord bot
Create a directory with python
[Python] Make a graph that can be moved around with Plotly
I made a package that can compare morphological analyzers with Python
[Road to Python Intermediate] Call a class instance like a function with __call__
Make a Spinbox that can be displayed in Binary with Tkinter
I made a shuffle that can be reset (reverted) with Python
Make a currency chart that can be moved around with Plotly (2)
Create a poster with matplotlib to visualize multiplication tables that remember multiplication
Make a Spinbox that can be displayed in HEX with Tkinter
Make a currency chart that can be moved around with Plotly (1)
Introduction of ls command lsix that can display a list of images