Play chess on Discord

Introduction

I have never left the area of ​​hobbies, so please kindly tell me if you can write more beautifully.

Thing you want to do

Allow chess matches on Discord using discord.py and chess packages

Preparation

Register at discord developer portal and get a token Install discord.py py -3 -m pip install -U discord.py` `` chess package install py -m pip install chess```

code

ChessBot.py



import discord
import chess
from discord.ext import commands

token = "token"

bot = commands.Bot(command_prefix="!")
board = None

@bot.event
async def on_ready():
    print("ready")

@bot.command()
async def start(ctx):
    global board
    board = chess.Board()
    await ctx.send("I created a board")
    await ctx.send("```" + str(board) + "```")

@bot.command()
async def move(ctx,movePos):
    global board
    if board == None:
        await ctx.send("The board has not been created")
        return
    try:
        board.push_san(movePos)
        await ctx.send("```" + str(board) + "```")
    except:
        await ctx.send(movePos + "Is not a valid value")
        a = ""
        for i in board.legal_moves:
            a += str(i) + ","
        await ctx.send("> " + a)
    if board.is_game_over():
        await ctx.send("game over")
        board = None

bot.run(token)

result

1.png

2.png

Where I stumbled

I wrote it correctly, but I get a lot of errors (connector.py and http.py)

Solutions

The cause seems to be that the SSL certificate has expired, so you can install a new certificate

  1. Run IE with administrator privileges
  2. Press the key mark to display the certificate
  3. Installation

Finally

When I couldn't get a valid value, I used `` `legal_moves``` to display the place where I could move as it was, but since unnecessary things were displayed, I turned it with for and combined. I feel that I can write the part over there neatly. Since user information can be acquired with ctx, I would like to use dict to make wins and losses for each user.

reference

https://discord.com/ https://pypi.org/project/chess/ https://teratail.com/questions/267889

Recommended Posts

Play chess on Discord
Play with Turtle on Google Colab
[Latest version] Play YouTube videos on discord.py!
Play MJ4 (Mahjong game) on Linux Mint 20