Make Yubaba with Discord.py

Introduction

@ Nemesis's Try to implement Yubaba in Java and @ nekozuki_dev's Try to implement Yubaba in Discord Bot This is the discord.py version of (http://qiita.com/nekozuki_dev/items/485d47a459a63f59400f). If you are new to discord.py, please read something like Practical Discord Bot in Python (discordpy explanation). (I don't think) This is the first article, so I'm sorry if there is something difficult to read. ** Light theme attention! ** **

Replace

Enter name

Scanner keiyakusho = new Scanner(System.in);
String name = keiyakusho.nextLine();

In the original, input is requested from the console like this,

ニックネーム

"You have a nickname!" That's why I will use a nickname this time.

output

System.out.println("From now on your name is"+newName+"It is. Mind you,"+newName+"That's right. I'll reply when I understand"+newName+"!!");

In the original, it only outputs the result, but since you can change the nickname in the Discord API, I will actually change the nickname.

Write code

I will actually write the code.

Basic bot

Use the one that is Official prepared.

import discord

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('$hello'):
        await message.channel.send('Hello!')

client.run('your token here')

Now you have a bot that responds when you send $ hello. Hello!

Make it react with mentions

User.mentioned_in (ClientUser.mentioned_in Use /ja/latest/api.html#discord.ClientUser.mentioned_in)) to make a mention judgment.

if message.content.startswith('$hello'):
  await message.channel.send('Hello!')

To

if client.user.mentioned_in(message):
  await message.channel.send('Hello!')

To メンションで反応 ~~ A precious scene where Yubaba speaks English ~~

Change the reaction

await message.channel.send('Hello!')

I will change here.


System.out.println("It's a contract. Write your name there.");

Scanner keiyakusho = new Scanner(System.in);
String name = keiyakusho.nextLine();

System.out.println("Hung."+name +"I mean. It's a luxurious name.");

Random random = new Random();
int newNameIndex = random.nextInt(name.length());
String newName = name.substring(newNameIndex,newNameIndex+1);

System.out.println("From now on your name is"+newName+"It is. Mind you,"+newName+"That's right. I'll reply when I understand"+newName+"!!");

This is the original code. If you rewrite this in Python,

import random
#~~~~~~~~~
print("It's a contract. Write your name there.")

name = input()

print(f"Hung.{name}I mean. It's a luxurious name.")

new_name = random.choice(name)

print(f"From now on your name is{new_name}It is. Mind you,{new_name}That's right. I'll reply when I understand{new_name}!!")

It will be like this. If you rewrite this to the discord.py specification ...

import random
#~~~~~~~~~
await message.channel.send("It's a contract. Write your name there.")

await message.channel.send(f"(You are in the contract`{message.author.display_name}`I wrote.)")

name = message.author.display_name

await message.channel.send(f"Hung.`{name}`I mean. It's a luxurious name.")

new_name = random.choice(name.replace(" ",""))

await message.channel.send(f"From now on your name is`{new_name}`It is."
f"Mind you,`{new_name}`That's right. I'll reply when I understand`{new_name}`!!")

await message.author.edit(nick=new_name)

await message.channel.send(f"(Your nickname is`{new_name}`Became.)")

It will be like this. はっや!!! (I am changing the server from here.) It's too early, so I'll keep you waiting for a while.

Make it low spec

Use asyncio.sleep to slow down the response. ** Note that if you don't use asyncio.sleep, the whole bot will stop! ** **

import random
import asyncio
#~~~~~~~~~
await message.channel.send("It's a contract. Write your name there.")
await asyncio.sleep(1)
await message.channel.send(f"(You are in the contract`{message.author.display_name}`I wrote.)")

name = message.author.display_name
await asyncio.sleep(2)
await message.channel.send(f"Hung.`{name}`I mean. It's a luxurious name.")

new_name = random.choice(name.replace(" ",""))
await asyncio.sleep(4)
await message.channel.send(f"From now on your name is`{new_name}`It is."
f"Mind you,`{new_name}`That's right. I'll reply when I understand`{new_name}`!!")

await message.author.edit(nick=new_name)

await message.channel.send(f"(Your nickname is`{new_name}`Became.)")

Now this. The result of incorporating this into the main code is ... 完成 I like it already completed! ~~ No objection ~~

Finally

I made Yubaba on discord.py. Since this is the first article, it may be difficult to read. In that case, please leave a comment.

Thank you for reading to the end.

This source

import discord
import random
import asyncio

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 client.user.mentioned_in(message):
        await message.channel.send("It's a contract. Write your name there.")
        await asyncio.sleep(1)
        await message.channel.send(f"(You are in the contract`{message.author.display_name}`I wrote.)")
        
        name = message.author.display_name
        await asyncio.sleep(2)
        await message.channel.send(f"Hung.`{name}`I mean. It's a luxurious name.")
        
        new_name = random.choice(name.replace(" ",""))
        await asyncio.sleep(4)
        await message.channel.send(f"From now on your name is`{new_name}`It is."
        f"Mind you,`{new_name}`That's right. I'll reply when I understand`{new_name}`!!")
        
        await message.author.edit(nick=new_name)
        
        await message.channel.send(f"(Your nickname is`{new_name}`Became.)")

client.run("your token here")

Supplement

Forbidden spits if the person who tried to do it has higher authority. If possible, that's a problem, so Yoshi!

Recommended Posts

Make Yubaba with Discord.py
Make Lambda Layers with Lambda
Make slides with iPython
Make sci-fi-like buttons with Kivy
Let's make Othello with wxPython
Easy to make with syntax
Make Puyo Puyo AI with Python
Output large log with discord.py
Let's make dice with tkinter
Make a fortune with Python
Make a fire with kdeplot
Make Slack chatbot with Errbot
Make Echolalia LINEbot with Python + heroku
Make apache log csv with python
Make ASCII art with deep learning
Let's make a GUI with python.
Make a sound with Jupyter notebook
Let's make a breakout with wxPython
Let's make Othello AI with Chainer-Part 1-
Make testing with Selenium more accessible
Make a recommender system with python
Make compute server diskless with LTSP
Make a filter with a django template
Let's make a graph with python! !!
Let's make a supercomputer with xCAT
Let's make Othello AI with Chainer-Part 2-
Make a model iterator with PySide
Make people smile with Deep Learning
Make Scrapy an exe with Pyinstaller
Make a nice graph with plotly
Make the Python console covered with UNKO
Make an audio interface controller with pyusb (2)
Let's make a shiritori game with Python
Make GUI apps super easy with tkinter
Make a rare gacha simulator with Flask
Make a Notebook Pipeline with Kedro + Papermill
Fractal to make and play with Python
Make a partially zoomed figure with matplotlib
Make a drawing quiz with kivy + PyTorch
Let's make a voice slowly with Python
Make PLEN Control Server compatible with ViVi PLEN2
Make pypy submission easier with atcoder-cli (python)
Make a cascade classifier with google colaboratory
Let's make a simple language with PLY 1
[Python] Let's make matplotlib compatible with Japanese
Make a logic circuit with a perceptron (multilayer perceptron)
Make a Yes No Popup with Kivy
Make a wash-drying timer with a Raspberry Pi
Make a GIF animation with folder monitoring
Let's make a web framework with Python! (1)
Let's make a tic-tac-toe AI with Pylearn 2
Make a desktop app with Python with Electron
Let's make a Twitter Bot with Python!
Make API of switchbot thermo-hygrometer with Node-RED
Let's make a web framework with Python! (2)
Make common settings with subplot of matplotlib