Make a BOT that shortens the URL of Discord

As the title says When the URL is long, when the preview is displayed at the YouTube URL, the above message will not be visible to people using smartphones. I made this BOT because I thought it was inconvenient. Made in python

Finished product

ピー - コピー.PNG ↑ BOT that when the URL is included in the message like this, it will be shortened if the reaction of the lower chain is pressed

Result ↓ キャプチャ.PNG

The whole program

import discord
import re
import asyncio
from urllib.parse import urlparse

#It's for this TOKEN test, so you can use it separately.
TOKEN = "NzA2MzQwNTMwMDE5MjM3OTQ0.Xq405w.pwRREjj-8N4MKph3QcV9NGb5EIM"
client = discord.Client()

@client.event
async def on_ready():
    print("Ready")

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

    pattern = "https?://[\w/:%#\$&\?\(\)~\.=\+\-]+"
    url_list = re.findall(pattern, message.content)
    if url_list != []:
        await message.add_reaction("⛓")
        return

@client.event
async def on_reaction_add(reaction, user):
    channel = client.get_channel(reaction.message.channel.id)
    if reaction.count >= 2 and reaction.emoji == "⛓":
        if reaction.count >= 3:
            pass
        else:
            s = reaction.message.content

            pattern = "https?://[\w/:%#\$&\?\(\)~\.=\+\-]+"
            url_list = re.findall(pattern, s)
            url_list[0]
            mes = s.strip(url_list[0])
            parsed_url = urlparse(url_list[0])
            site = '{uri.scheme}://{uri.netloc}/'.format(uri=urlparse(url_list[0]))


            embed = discord.Embed(title=f"{mes}",
                description=f"[Short URL]({url_list[0]})",
                color=0x87cefa)
            embed.set_author(name=reaction.message.author.display_name,
                icon_url=reaction.message.author.avatar_url_as(format="png"))
            embed.set_footer(text=f"{site}")

            await channel.send(embed=embed)
    return

client.run(TOKEN)

(I wrote it hard) Commentary

** First one **

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

    #This ↑ this ↓
    pattern = "https?://[\w/:%#\$&\?\(\)~\.=\+\-]+"
    url_list = re.findall(pattern, message.content)
    if url_list != []: #Whether the list is empty
        await message.add_reaction("⛓")
        return

This is the place that is called when a message comes, and the favorite is from this ↑ this ↓. The program from this ↑ this ↓ puts the URL included in the message in the list. If the list is empty, add a reaction. The URL guy http://trelab.info/python/python-%E6%AD%A3%E8%A6%8F%E8%A1%A8%E7%8F%BE%E3%81%A7url%E3%81%AE%E4%B8%80%E8%87%B4%E3%83%81%E3%82%A7%E3%83%83%E3%82%AF%E3%80%81%E6%8A%BD%E5%87%BA%E3%82%92%E8%A1%8C%E3%81%86/ Refer to ... No, I'm sorry.

The second

@client.event
async def on_reaction_add(reaction, user):
    channel = client.get_channel(reaction.message.channel.id)
    if reaction.count >= 2 and reaction.emoji == "⛓":
        if reaction.count >= 3:
            pass
        else:
            s = reaction.message.content
            #This ↑ this ↓
            pattern = "https?://[\w/:%#\$&\?\(\)~\.=\+\-]+"
            url_list = re.findall(pattern, s)
            url_list[0]
            mes = s.strip(url_list[0])
            parsed_url = urlparse(url_list[0])
            site = '{uri.scheme}://{uri.netloc}/'.format(uri=urlparse(url_list[0]))


            embed = discord.Embed(title=f"{mes}",
                description=f"[Short URL]({url_list[0]})",
                color=0x87cefa)
            embed.set_author(name=reaction.message.author.display_name,
                icon_url=reaction.message.author.avatar_url_as(format="png"))
            embed.set_footer(text=f"{site}")

            await channel.send(embed=embed)
    return

Where there is a program to send a shortened URL. Called when a reaction is attached. The favorite is from the place where this ↑ this ↓ is written Before that, the one who determines whether the reaction is a chain After this ↑ this ↓

pattern = "https?://[\w/:%#\$&\?\(\)~\.=\+\-]+"
url_list = re.findall(pattern, s)
url_list[0]
#This ↑ this ↓
mes = s.strip(url_list[0])#Take the URL from the message
parsed_url = urlparse(url_list[0])#Remove the extra from the URL
site = '{uri.scheme}://{uri.netloc}/'.format(uri=urlparse(url_list[0]))

Is almost the same as the one I did in the first one After this ↑ this ↓, the URL is taken from the message and the extra one is removed from the URL. The one who removes the extra from the URL https://www.python.ambitious-engineer.com/archives/35 Refer to ...

embed = discord.Embed(title=f"{mes}",
    description=f"[Short URL]({url_list[0]})",
    color=0x87cefa)
embed.set_author(name=reaction.message.author.display_name,
    icon_url=reaction.message.author.avatar_url_as(format="png"))
embed.set_footer(text=f"{site}")

await channel.send(embed=embed)

This is the one that sends the shortened one with embed

This completes

Finally

Hmm can not think of

the end

Recommended Posts

Make a BOT that shortens the URL of Discord
Let's make a Discord Bot.
Create a bot that only returns the result of morphological analysis with MeCab on Discord
I made a slack bot that notifies me of the temperature
Make a Discord Bot that you can search for and paste images
Make a copy of the list in Python
Create a BOT that displays the number of infected people in the new corona
I tried to make a translation BOT that works on Discord using googletrans
[Discode Bot] I created a bot that tells me the race value of Pokemon
The story of making a Line Bot that tells us the schedule of competitive programming
How to make a Raspberry Pi that speaks the tweets of the specified user
The story of launching a Minecraft server from Discord
A story that reduces the effort of operation / maintenance
[Python] A program that counts the number of valleys
Make a note of the list of basic Pandas usage
# Function that returns the character code of a string
LINE Bot that notifies you of the stocks of interest
Generate that shape of the bottom of a PET bottle
A story that analyzed the delivery of Nico Nama.
[Python] A program that compares the positions of kangaroos.
The world's most easy-to-understand explanation of how to make a LINE BOT (1) [Account preparation]
Make a LINE BOT (chat)
I made a discord bot
A tool that automatically turns the gacha of a social game
Let's make the analysis of the Titanic sinking data like that
Let's execute the command on time with the bot of discord
Let's make a robot that solves the Rubik's Cube! 2 Algorithm
Let's make a robot that solves the Rubik's Cube! 3 Software
Let's make a robot that solves the Rubik's Cube! 1 Overview
The story of making a question box bot with discord.py
A Python script that compares the contents of two directories
[Completed] bot that posts the start notification of Nico Nico Live Broadcasting to Discord on discord.py
[Concept] bot that posts the start notification of Nico Nico Live Broadcasting to Discord on discord.py
How to make an interactive LINE BOT 004 (answer the closing date of a listed company)
I created a Discord bot on Docker that reports the number of corona infected people in Tokyo at a specified time.
A memo that reproduces the slide show (gadget) of Windows 7 on Windows 10.
When incrementing the value of a key that does not exist
I tried to make a site that makes it easy to see the update information of Azure
pandas Fetch the name of a column that contains a specific character
I made a Line bot that guesses the gender and age of a person from an image
A formula that simply calculates the age from the date of birth
How to make a slack bot
Created a Discord bot to notify you of updates to become a novelist
A function that measures the processing time of a method in python
[Python] Make the function a lambda function
The story of creating a site that lists the release dates of books
Get the URL of a JIRA ticket created with the jira-python library
I made a Discord chat reading bot by imitating the appearance
[python] A note that started to understand the behavior of matplotlib.pyplot
The story of writing a program
The story of making a module that skips mail with python
The story of creating a bot that displays active members in a specific channel of slack with python
[Python] A program that rotates the contents of the list to the left
Create a bot that posts the number of people positive for the new coronavirus in Tokyo to Slack
Create a BOT that can call images registered with Discord like pictograms
[Python] A program that calculates the number of chocolate segments that meet the conditions
The story of making a university 100 yen breakfast LINE bot with Python
I made a calendar that automatically updates the distribution schedule of Vtuber
[Python] A program that calculates the number of socks to be paired
How to make a rock-paper-scissors bot that can be easily moved (commentary)
I made a Discord bot in Python that translates when it reacts