티스토리 뷰

개발

디스코드 봇 업데이트

KWG07(joseph0528) 2021. 5. 15. 22:45

한동안 디스코드 봇 글을 안 썼었는데 오랜만에 다시 씁니다

 

전과 바뀐 점이라고 하면 전까지는 솔브드에서 직접 정보를 얻어왔는데 알고 보니 솔브드 api만 써야 된다고 해서 솔브드를 쓰는 대부분의 코드를 api로 바꿔놨다.

https://solvedac.github.io/unofficial-documentation/

 

Swagger UI

 

solvedac.github.io

이건 솔브드 api 링크다

ps 관련해서는 문제 검색이 조금 바뀌었는데 누가 검색했는지 상단에 나오게 해 놨고 태그도 스포일러 처리를 해서 같이 출력하게 해 놨다 또 정답률 이런 거는 사용하면 안 된다고 해서 다 지워놨다. 나머지는 딱히 전과 바뀐 점은 없다

 

 

또 추가된 점은 좀 잡다한 기능이지만 ~write 하고 영어를 입력하면 영어를 저렇게 나타내 주는데 영어 말고도 숫자, 느낌표, 물음표가 추가로 가능하다

 

그리고 다른 봇에 있던 2048게임도 이봇에 추가해놨고 이걸 사용하는 서버에서 하도 이유 없는 뮤트를 많이 당해서 봇으로 테스트 방에서 bot_chatting_on이라고 입력하면 이 봇이 연결되어있는 모든 방의 채팅이 다 한 채널로 오게 했는데 이때 ~msgid_change 서버 id 하면 ~send를 할 때 해당 서버로 보낼 수 있게 했다.

~send는 지금 선택된 서버에 채팅을 치는 것이다.

 

그리고 백준을 사용한 내기 시스템도 만들고 있다.

import discord
import atexit
import requests
import random
import urllib.request as req
from bs4 import BeautifulSoup
import emoji
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import openpyxl
from discord.utils import get
import bi
import math
import token
import json
from tkinter import *
from tkinter import messagebox
from urllib.error import URLError,HTTPError
import asyncio
client=discord.Client()
def boj(ex):
    if len(ex)==1:return ["https://www.acmicpc.net/",-9]
    else:
        if ex[1]=="profile"or ex[1]=="프로필":
            if len(ex)==3:
                q="https://www.acmicpc.net/user/"+ex[2]
                return [q,1]
        elif ex[1]=="rank"or ex[1]=="랭크"or ex[1]=="순위":
            return [0,2]
            #if len(ex)==2:
            #    return ["https://www.acmicpc.net/ranklist",2]
            #else:
            #    page="https://www.acmicpc.net/ranklist/"+ex[2]
            #    return [page,2]
        elif ex[1]=="search"or ex[1]=="검색":
            page="https://www.acmicpc.net/problemset?search="
            searchname=""
            for i in range(2,len(ex)):
                searchname+=ex[i]+"+"
            page+=searchname
            #print(page)
            return [page,4]
        else:
            q="https://www.acmicpc.net/problem/"+ex[1]
            return [q,3]

def link(x,soup):
    return soup.select_one(x).string

def solved(ex):
    if len(ex)==1:return "https://solved.ac"
    else:
        if ex[1]=="profile"or ex[1]=="프로필":
            if len(ex)==3:
                q="https://solved.ac/profile/"+ex[2]
                return q
        else:
            if(len(ex)==3 or len(ex)==4)and (ex[1]=="rank"or ex[1]=="랭크"or ex[1]=="순위"):
                if ex[2]=="ti"or ex[2]=="티어":
                    if len(ex)==3:page="https://solved.ac/ranking/tier"
                    else:page="https://solved.ac/ranking/tier?page="+ex[3]
                if ex[2]=="cl"or ex[2]=="클래스":
                    if len(ex)==3:page="https://solved.ac/ranking/class"
                    else:page="https://solved.ac/ranking/class?page="+ex[3]
                if ex[2]=="co"or ex[2]=="기여도":
                    if len(ex)==3:page="https://solved.ac/ranking/contribution"
                    else:page="https://solved.ac/ranking/contribution?page="+ex[3]
                return page
            
def deln(ip):
    if ip=="guncgung"or ip=="papergundam"or ip=="guncgung"or ip=="gunchoong"or ip=="guncgung":return False
    for i in range(len(ip)):
        if ip[i]=="건"or ip[i]=="충"or ip[i]=="gun"or ip[i]=="고"or ip[i]=="원"or ip[i]=="규"or ip[i]=="추ᇰ"or ip[i]=="ㄱㅓㄴ"or ip[i]=="거ᇈ":return False
    return True
def gymanst(ip):
    if ip.find("바보")>=0:return True
    if ip.find("못하")>=0:return True
    if ip.find("기만")>=0 and ip.find("아닌")>=0:return True
    return False
qh=0
def chan(qh):
    global soup
    #print("qh",qh)
    tp=qh
    tp=max(tp,1)
    pagenumber=(tp-1)//10+1
    url="https://www.acmicpc.net/ranklist/"+str(pagenumber)
    try:             
        res=req.urlopen(url).read()
        soup=BeautifulSoup(res,'html.parser')
        qr=""
        co=(tp*10-9)%100
        for i in range(co,co+10):
            qr+=str(link("#ranklist > tbody > tr:nth-child("+str(i)+") > td:nth-child(1)",soup))+". "
            name12=str(soup.select_one("#ranklist > tbody > tr:nth-child("+str(i)+") > td:nth-child(2) > a"))
            qty=15
            name1=""
            while 1:
                if name12[qty]!="\"":name1+=name12[qty]
                else:break
                qty+=1
            qr+=name1+" ("
            qr+=str(link("#ranklist > tbody > tr:nth-child("+str(i)+") > td:nth-child(4) > a",soup))+"문제)\n"
        return [qr,0]
        #msg=await message.channel.send(message.channel,embed=discord.Embed(title="",description=qr,color=0x62c1cc))
        #await msg.add_reaction("\U00002B05")
        #await msg.add_reaction("\U000027A1")
    except HTTPError as e:
        return ["잘못 입력하셨습니다.",1]
        #await message.channel.send("잘못 입력하셨습니다.")
def ac(usern,pb):
    #!solved_by:joseph0528 1001
    urrl="https://api.solved.ac/v2/search/recommendations.json?query=!solved_by%3A"+usern+"%20"+pb
    res11=requests.get(urrl)
    soup11=str(BeautifulSoup(res11.text,'html.parser'))
    soup11=soup11.replace("'","\"")
    jsonData1=json.loads(soup11)
    if len(jsonData1['result']["problems"])==0:return 1
    else:return 0

@client.event
async def on_ready():
    #sq=token.f(0)
    #print(sq)
    print("Start {0.user}".format(client))
system=0
tier=["언레","브론즈 5","브론즈 4","브론즈 3","브론즈 2","브론즈 1",\
    "실버 5","실버 4","실버 3","실버 2","실버 1",\
    "골드 5","골드 4","골드 3","골드 2","골드 1",\
    "플래티넘 5","플래티넘 4","플래티넘 3","플래티넘 2","플래티넘 1",\
    "다이아 5","다이아 4","다이아 3","다이아 2","다이아 1",\
    "루비 5","루비 4","루비 3","루비 2","루비 1","마스터"]
tierimagelink=["<:unranked:828174300338585600>","<:bronze5:828174299247673345>","<:bronze4:828174298963116092>","<:bronze3:828174299269169183>","<:bronze2:828174300301099028>","<:bronze1:828174299239415828>",\
    "<:silver5:828174300502294549>","<:silver4:828174300057698325>","<:silver3:828174301088710716>","<:silver2:828174300329541632>","<:silver1:828174300120088619>",\
    "<:gold5:828174299843788811>","<:gold4:828174299630010398>","<:gold3:828174299944452116>","<:gold2:828174299722547200>","<:gold1:828174299210055711>",\
    "<:platinum5:828174300355493888>","<:platinum4:828174299750858762>","<:platinum3:828174300225077258>","<:platinum2:828174300401369088>","<:platinum1:828174299713765386>",\
    "<:diamond5:828174299419901972>","<:diamond4:828174299264843816>","<:diamond3:828174298950008833>","<:diamond2:828174299222245386>","<:diamond1:828174299298005002>",\
    "<:ruby5:828174300305293422>","<:ruby4:828174299772616715>","<:ruby3:828174300392718346>","<:ruby2:828174299901984768>","<:ruby1:828174300338323506>","<:master:828199362868936724>"]
classimage=["<:class0:830666108943204393>","<:class1:830666109027483709>","<:class1silver:830666109412966431>","<:class1gold:830666110830903348>",\
            "<:class2:830666109316628480>","<:class2silver:830666110969839636>","<:class2gold:830666110469799947>",\
            "<:class3:830666109169958952>","<:class3silver:830666109723082753>","<:class3gold:830666110491820042>",\
            "<:class4:830666109455302746>","<:class4silver:830666110009344010>","<:class4gold:830666110214078484>",\
            "<:class5:830666109404839984>","<:class5silver:830666110214078494>","<:class5gold:830666110521180201>",\
            "<:class6:830666109450846239>","<:class6silver:830666110151163934>","<:class6gold:830666110340169728>",\
            "<:class7:830666109850091530>","<:class7silver:830666110226923570>","<:class7gold:830666110520000524>",\
            "<:class8:830666109903962122>","<:class8silver:830666109870538823>","<:class8gold:830666110827102218>",\
            "<:class9:830666109770268693>","<:class9silver:830666110306222091>","<:class9gold:830666110335582218>",\
            "<:class10:830666110176723015>","<:class10silver:830666109887184897>","<:class10gold:830666110302158848>"]
tierimagehtml=["https://cdn.discordapp.com/emojis/828174300338585600.png?v=1","https://cdn.discordapp.com/emojis/828174299247673345.png?v=1",\
               "https://cdn.discordapp.com/emojis/828174298963116092.png?v=1","https://cdn.discordapp.com/emojis/828174299269169183.png?v=1",\
               "https://cdn.discordapp.com/emojis/828174300301099028.png?v=1","https://cdn.discordapp.com/emojis/828174299239415828.png?v=1",\
               "https://cdn.discordapp.com/emojis/828174300502294549.png?v=1","https://cdn.discordapp.com/emojis/828174300057698325.png?v=1",\
               "https://cdn.discordapp.com/emojis/828174301088710716.png?v=1","https://cdn.discordapp.com/emojis/828174300329541632.png?v=1",\
               "https://cdn.discordapp.com/emojis/828174300120088619.png?v=1","https://cdn.discordapp.com/emojis/828174299843788811.png?v=1",\
               "https://cdn.discordapp.com/emojis/828174299630010398.png?v=1","https://cdn.discordapp.com/emojis/828174299944452116.png?v=1",\
               "https://cdn.discordapp.com/emojis/828174299722547200.png?v=1","https://cdn.discordapp.com/emojis/828174299210055711.png?v=1",\
               "https://cdn.discordapp.com/emojis/828174300355493888.png?v=1","https://cdn.discordapp.com/emojis/828174299750858762.png?v=1",\
               "https://cdn.discordapp.com/emojis/828174300225077258.png?v=1","https://cdn.discordapp.com/emojis/828174300401369088.png?v=1",\
               "https://cdn.discordapp.com/emojis/828174299713765386.png?v=1","https://cdn.discordapp.com/emojis/828174299419901972.png?v=1",\
               "https://cdn.discordapp.com/emojis/828174299264843816.png?v=1","https://cdn.discordapp.com/emojis/828174298950008833.png?v=1",\
               "https://cdn.discordapp.com/emojis/828174299222245386.png?v=1","https://cdn.discordapp.com/emojis/828174299298005002.png?v=1",\
               "https://cdn.discordapp.com/emojis/828174300305293422.png?v=1","https://cdn.discordapp.com/emojis/828174299772616715.png?v=1",\
               "https://cdn.discordapp.com/emojis/828174300392718346.png?v=1","https://cdn.discordapp.com/emojis/828174299901984768.png?v=1",\
               "https://cdn.discordapp.com/emojis/828174300338323506.png?v=1","https://cdn.discordapp.com/emojis/828199362868936724.png?v=1"]
tiercolor=[0x2d2d2d, 0xad5600, 0x435f7a, 0xec9a00, 0x27e2a4, 0x00b4fc, 0xff0062, 0xFFFFFF]
            
msg1=""
numm=[":zero:",":one:",":two:",":three:",":four:",":five:",":six:",":seven:",":eight:",":nine:"]
image_sort=open("image_sort.txt","r")
line=image_sort.readlines()
sort_message=[]
for i in range(len(line)):
    content=str(line[i][:len(line[i])-1]).split()
    #print(content)
    sort_message.append([content[0],content[1]])
image_sort.close()
message_len=len(sort_message)
#print("!@#!@#")
tile=["<:0:814871915004821504>","<:2:814857792178749440>",
      "<:4:814866255446147124>","<:8:814866255831629874>",
      "<:16:814866255886286889>","<:32:814869453988823070>",
      "<:64:814869454529363988>","<:128:814869454528708609>",
      "<:256:814869454948925470>","<:512:814869454579695646>",
      "<:1024:814869454647197747>","<:2048:814869455107653652>",
      "<:4096:814869454043349042>","<:8192:814869454911438890>",
      "<:16384:814869455078293554>","<:32768:814869453967327262>",
      "<:65536:814869454918778931>","<:131072:814869455464693780>"]
blobaww=["<:leftup:817726462899388444>","<:rightup:817726463070699581>",
         "<:leftdown:817726462927831041>","<:rightdown:817726463117623296>"]
gp=0
gamescore=0
player=""
msg11=0
msg22=0
l=[]
playerlist={}
playermsg={}
dy=[-1,-1,-1,0,1,1,1,0]
dx=[-1,0,1,1,1,0,-1,-1]
yy=[-1,0,1,0]
xx=[0,1,0,-1]
def pt():
    global l,gamescore
    pr=""
    rdm=random.randint(1,10)
    val=0
    if rdm==1:val=4
    else:val=2
    xy=[]
    for i in range(4):
        for g in range(4):
            if l[i][g]==0:xy.append([i,g])
    if len(xy)!=0:
        ag=random.randint(0,len(xy)-1)
        l[xy[ag][0]][xy[ag][1]]=val
    for i in range(4):
        for g in range(4):
            if l[i][g]==0:
                pr+=tile[0]
            else:
                pr+=tile[int(math.log2(l[i][g]))]
        pr+="\n"
    #print(pr)
    cq=0
    for i in range(4):
        for g in range(4):
            if l[i][g]==0:cq=1
            else:
                if i==1 or i==2:
                    if l[i][g]==l[i-1][g]:return[pr,0]
                    if l[i][g]==l[i+1][g]:return[pr,0]
                if g==1 or g==2:
                    if l[i][g]==l[i][g-1]:return[pr,0]
                    if l[i][g]==l[i][g+1]:return[pr,0]
    if cq==0:return[pr,1]
    else:return[pr,0]
chatting=0
sendmessageid=840886579593347072

@client.event
async def on_message(message):
    global system,qh,msg1,tier,numm,logfile,image_sort,line,sort_message,message_len,tiercolor,chatting,sendmessageid
    global l,gp,gamescore,player,msg11,msg22,blobaww,playerlist
    if message.author==client.user:return

    if message.content.startswith("~ps_bet"):
        tier=message.content[8:]
        msa=await message.channel.send("!")
        await msa.add_reaction('👍') 
        msa.delete()
        
        def check(reaction,user):
            print(user)
            return user==message.author and str(reaction.emoji)=='👍'
        try:
            reaction,user=await client.wait_for('reaction_add',timeout=10.0,check=check)
        except asyncio.TimeoutError:
            await message.channel.send('👎')
            #msa.delete()
        else:
            await message.channel.send('👍')
        #msa.delete()

    if message.content.startswith("~msgid_change")and chatting==1:
        af=message.content[14:]
        sendmessageid=int(af)
        channel=client.get_channel(840814452278558750)
        await channel.send("변경이 완료되었습니다")
        
    if message.content.startswith("~send")and chatting==1:
        try:
            af=message.content[6:]
            channel=client.get_channel(sendmessageid)#788218400275038219)#788579938239250462)#=테스트서버
            await channel.send(af)
        except:
            channel=client.get_channel(840814452278558750)
            await channel.send("서버 id가 잘못되었습니다")
        
    if chatting==1:
        #print(message.channel.id)
        channel=client.get_channel(840814452278558750)#=테스트서버#840886579593347072
        #print(message.channel.id)
        af=str(message.author)+" : "+str(message.content)+"\n"+str(message.guild.name)+"\n"+str(message.channel)+"\n"+str(message.channel.id)
        
        await channel.send(af)
        #if str(meeage.author)==
        #print(message.content)
        #print(message.channel)
        #print(message.channel.id)
        #await message.channel.send(asd.channel.id)
    if message.content.startswith("bot_chatting_on"):chatting=1;#channel="788579938239250462";await message.channel.send(message.channel.id)
    if message.content.startswith("bot_chatting_off"):chatting=0   
        
    if message.content.startswith("~hell"):
        my_name = discord.utils.get(message.guild.members, name="건충")
        await message.channel.send("{} Python Bot에 의해 출력됨.".format(my_name.mention))
    #print("!@#!@#!@#!@#!@#!@#")
    #if str(message.author.id)=="653027910395101195"or str(message.author.id)=="363532983811964929":return
    #2048
    if message.content.startswith("~ranking_2048"):
        await message.channel.send("점검중입니다")
        return
        File=open('ranking.txt','r')#,encoding='utf-8')
        line=File.readlines()
        if len(line)==0:
            await message.channel.send("아무도 없습니다")
        else:
            rank=[]
            for i in range(len(line)):
                qgf=line[i].split(":")
                #print(qgf)
                rank.append([int(qgf[1]),qgf[0]])
            rank.sort(reverse=True)
            rankmessage=""
            for i in range(min(len(line),10)):
                rankmessage+=str(i+1)+"위 : "+rank[i][1]+", "+str(rank[i][0])+"점\n"
            Embed=discord.Embed(title="help",description=rankmessage,color=0x62c1cc)
            await message.channel.send(embed=Embed)
        File.close()

    if message.content.startswith("~stop 2048"):
        await message.channel.send("점검중입니다")
        return
        if str(message.author.id)==player or str(message.author.id)=="736113209991233537":
            await message.channel.send("game stop")
            File=open('ranking.txt','a')
            print(str(message.author)+":"+str(gamescore),file=File)
            File.close()
            Embed=discord.Embed(title="Game over",description="Your score is "+str(gamescore),color=0x62c1cc)
            await message.channel.send(embed=Embed)
            gp=0
        
    if message.content.startswith("~start 2048"):
        await message.channel.send("점검중입니다")
        return
        if gp==0:
       # try:
       #     qtyui=player[str(message.author.id)][0]
       #     await message.channel.send("게임 플레이 중입니다")
       # except:
            gamescore=0
            player=str(message.author.id)
            #print(player)
            l=[[0 for i in range(4)]for g in range(4)]
            #l=[[16,32,4096,8192],[8,64,2048,16384],[4,128,1024,32768],[4,256,512,65536]]

            pr1=pt()
            gp=1
            af=""
            #player[str(message.author.id)]=[0,l]
            msg22=await message.channel.send("**"+str(gamescore)+"점**\n")
            msg11=await message.channel.send(pr1[0])
            await msg11.add_reaction("\U00002B06")#up
            await msg11.add_reaction("\U00002B07")#down
            await msg11.add_reaction("\U00002B05")#left
            await msg11.add_reaction("\U000027A1")#right
        else:
            await message.channel.send("게임 플레이 중입니다")
            #file=open(str(message.guild.id)+'.txt','r')
        #print(file.readlines())
        #str(message.guild.id)+'.txt'
        #while 1:
        #qt=game_2048.game(l)
        #print("#",qt)
        #await message.channel.send(qt)


    #2048

    #if not message.content.startswith("~"):
    #    if str(message.guild.name)=="원석방":
    #        if str(message.channel.id)=="840886579593347072":
    #            for i in range(message_len):
    #                #print("##ASD")
    #                #print(sort_message[i][0])
    #                if sort_message[i][0]in message.content:
    #                    await message.channel.send(sort_message[i][1])
    #                    break
    #    else:
    #        for i in range(message_len):
    #            #print("##ASD")
    #            #print(sort_message[i][0])
    #            if sort_message[i][0]in message.content:
    #                await message.channel.send(sort_message[i][1])
    #                break
    #print(meessage.content)

    if message.content.startswith("~apt_list"):
        image_sort=open("image_sort.txt","r")
        lines=image_sort.readlines()
        ms1=""
        for i in range(message_len):
            try:
                content=str(lines[i][:len(lines[i])-1]).split()
                ms1+=content[0]+" : "+content[1]+"\n\n"
            except:
                break
        await message.channel.send(embed=discord.Embed(title="list",description=ms1,color=0x62c1cc))
        image_sort.close()
        

    if message.content.startswith("~apt_delete"):
        if str(message.author.id)=="736113209991233537":#or str(message.author.id)!="736113209991233537":
            ex=message.content[12:].split()
            image_sort=open("image_sort.txt","r")
            lines=image_sort.readlines()
            #print(lines)
            update=""
            update_change=0
            for i in range(message_len):
                content=str(lines[i][:len(lines[i])-1]).split()
                if ex[0]==content[0]:
                    if i!=message_len-1:
                        update+="\n"
                    for g in range(i+1,message_len):
                        update+=lines[g][:len(lines[g])-1]
                        if g!=message_len-1:
                            update+="\n"
                    image_sort.close()
                    image_sort=open("image_sort.txt","w")
                    print(update,file=image_sort)
                    update_change=1
                    sort_message.pop(i)
                    message_len-=1
                    await message.channel.send("메세지가 지워졌습니다")
                    break
                else:
                    if i!=0:
                        update+="\n"
                update+=lines[i][:len(lines[i])-1]
            if update_change==0:
                await message.channel.send("그런 메세지가 없습니다")
            image_sort.close()
        else:
            await message.channel.send("개발자가 아닙니다")
    
    if message.content.startswith("~apt_add"):
        try:
            #print("ASD")
            chke=0
            ex=message.content[9:].split()
            #print(ex)
            image_sort=open("image_sort.txt","r")
            lines=image_sort.readlines()
            #print(lines)
            for i in range(message_len):
                content=str(lines[i][:len(lines[i])-1]).split()
                #print(content)
                if ex[0]==content[0]:
                    await message.channel.send("이미 있는 문자입니다")
                    chke=1
                    break
                #if ex[1]==content[1]:
                #    await message.channel.send("이미 있는 이모지입니다")
                #    chke=1
                #    break
            image_sort.close()
            if chke==0:
                image_sort=open("image_sort.txt","a")
                user_id=message.author.id
                #print(user_id)
                print(str(ex[0]+" "+ex[1]+" "+str(user_id)),file=image_sort)
                await message.channel.send("추가되었습니다")
                sort_message.append([ex[0],ex[1]])
                message_len+=1
                image_sort.close()
        except:
            ASD=0
            
            
            
    
    if message.content.startswith("~print"):
        await message.channel.send("<:ruby2:828174299901984768>")

    if message.content.startswith("~write"):
        try:
            prnt=""
            agg=0
            ex=message.content[7:].split()
            #print(message.content[7:].split())
            for i in range(len(ex)):
                for g in range(len(ex[i])):
                    sss=ex[i][g].lower()
                    #print(sss)
                    if 1<=ord(sss)-96<=26:
                        prnt+=":regional_indicator_"+sss+":"
                    elif ex[i][g]==" ":
                        prnt+=" "
                    elif 1<=ord(sss)-47<=10:
                        prnt+=numm[int(ex[i][g])]
                    elif ex[i][g]=="?":
                        prnt+=":question:"
                    elif ex[i][g]=="!":
                        prnt+=":exclamation:"
                    else:
                        await message.channel.send("영어와 숫자만 됩니다")
                        agg=1
                        break
                if agg==1:break
                prnt+="\n"
            if agg==0:
                await message.channel.send(prnt)
        except:
            await message.channel.send("입력이 너무 큽니다")

    
    #if message.content.startswith("1124579410016957024519240651218144"):
    #    await message.channel.send("귀여운 곤충 >_<")
        #emo=emoji.emojize(":regional_indicator_a:")
        #await message.channel.send(str(emo))
        
    if message.content.startswith("~add"):
        try:
            ex=message.content[5:].split()
            url="https://www.acmicpc.net/user/"+ex[0]
            res=req.urlopen(url)
            res=res.read()
            soup=BeautifulSoup(res,'html.parser')
            userip=str(message.author).split("#")
            nm=bi.add(ex[0],"#"+userip[1])
            if nm==0:
                await message.channel.send("한사람당 한 계정만 추가 가능합니다.")
            else:
                await message.channel.send("추가 완료되었습니다.")
        except HTTPError as e:
                await message.channel.send("아이디가 잘못되었습니다.")
                
    #if str(message.author).split("#")[1]=="9311":
    #    await message.channel.send("정후님 잼민이~")
     
    if message.content.startswith("~good"):q="good";await message.channel.send("\U0001F44D")

    #if message.content.startswith("서버 이름"):await message.channel.send(message.guild);await message.channel.send(message.channel);await message.channel.send(message.author)

    
    if message.content.startswith("갓"):
        await message.add_reaction("↖")
        #e=emoji.emojize("\:arrow_up:")
        #await message.channel.send(e)
    
    if message.content.startswith("마자효"):q="마자효\n1104";await message.channel.send(q)
    
    if message.content.startswith("~system"):
        userip=str(message.author).split("#")
        if not deln(userip[0]):
            msg=message.content[8:].split()
            if len(msg)==1:
                if msg[0]=="on":system=1
                elif msg[0]=="off":system=0
                else:await message.channel.send("please say on or off")
                if msg[0]=="on"or msg[0]=="off":await message.channel.send("on" if system==1 else "off")
        else:
            await message.channel.send("당신은 관리자가 아닙니다")

    if message.content.startswith("~fan"):
        msg=message.content[5:];msg+="님 팬이에요";await message.channel.send(msg)

    if message.content.startswith("~cute"):
        #await message.channel.send("누군가 때문에 지움 ㅅㄱ")
        msg=str(message.content[6:])
        if system==0:
            if deln(msg):msg+="님 귀여워요~";await message.channel.send(msg)
            else:await message.channel.send("그 이름은 금지 되어있습니다")
        else:
            msg+="님 귀여워요~";await message.channel.send(msg)

    if message.content.startswith("~help"):
        ms=""
        ms+="팬이에요 : ~fan nickname\n\n"
        ms+="귀여워요:~cute nickname\n\ngood:~good\n\ngod:~god nickname\n\n"
        ms+="지원하는 사이트:baekjoon(boj)(백준)\n\n"
        ms+="ps site:~ps sitename\n\npssite number:~ps sitename number\n\n"
        ms+="ps site profile:~ps sitename profile name\n\n"
        ms+="ps site rank:~ps sitename rank pagenumber\n\n"
        ms+="solved.ac rank tier:~ps solved.ac rank (ti or 티어) pagenumber\n\n"
        ms+="solved.ac rank class:~ps solved.ac rank (cl or 클래스) pagenumber\n\n"
        ms+="solved.ac rank contribution(기여도):~ps solved.ac rank (co or 기여도) pagenumber\n\n"
        ms+="ps codeforces rank korea:~ps codeforces rank korea pagenumber\n\n"
        ms+="ps sitename search:~ps sitename search_name(검색할 단어)\n\n"
        ms+="영어 입력 이모티콘으로 출력 : ~write 내용\n\n"
        #ms+="백준 해당 문제 제출기록:~ps boj stat 문제번호\n\n"
        msg=await message.channel.send(message.channel,embed=discord.Embed(title="test bot help",description=ms,color=0x62c1cc))
        await msg.edit(content="")
        
    #if message.content.startswith("~gyman"):
    #    #await message.channel.send("별게 다 뚫리네ㅡㅡ")
    #    msg=str(message.content[7:])
    #    if system==0 and not deln(msg):
    #        await message.channel.send("기만이 아닙니다")
    #    else:
    #        msg+="님 기만";await message.channel.send(msg)
        
    if message.content.startswith("~god"):
        msg=str(message.content[5:])
        if system==0:
            if deln(msg):msg+="님 갓";await message.channel.send(msg)
            else:await message.channel.send("갓이 아닙니다")
        else:
            msg+="님 갓";await message.channel.send(msg)
        
    if message.content.startswith("~ps"):
        #await message.channel.send("\ud130\ub81b")
        ex=message.content[4:].split()
        if len(ex)!=0:
            if ex[0]=="boj"or ex[0]=="baekjoon"or ex[0]=="백준":
                File=open("boj.txt","r")
                line=File.readlines()
                qa=line[0][:len(line[0])-1].split(",")
                userip=str(message.author).split("#")
                if "#"+userip[1] in qa:
                    index=qa.index("#"+userip[1])
                    usern=line[index+1][:len(line[index+1])-1]
                    #print(usern)
                    qy=boj(ex)
                    if qy[1]==3:
                        try:
                            url1='https://api.solved.ac/v2/problems/show.json?id='+ex[1]
                            res1=requests.get(url1)
                            soup1=str(BeautifulSoup(res1.text,'html.parser'))
                            soup1=soup1.replace("'","\"")
                            jsonData=json.loads(soup1)
                            #print(jsonData)
                            problems=jsonData["result"]["problems"][0]
                            url="https://www.acmicpc.net/problem/"+ex[1]
                            nm=url+"\n\n"
                            nm+="푼 사람 수 : "+str(problems['solved_count'])+"\n\n"
                            
                            #print('https://solved.ac/search?query='+ex[1])
                            #jsonData=json.loads(soup1.find('script', {'type':'application/json'}).string)['props']['pageProps']
                            solved=ac(usern,ex[1])


                            #req1=requests.get('https://www.acmicpc.net/user/'+usern)
                            #soup1=BeautifulSoup(req1.text,'html.parser')
                            #jsonData=json.loads(soup1.find('script', {'type':'application/json'}).string)['props']['pageProps']

                            #!solved_by:joseph0528 1001 api에서 이거로 탐색
                            if solved==1:nm="```diff\n+맞은문제+\n```\n"+nm
                            else:nm="```\n안푼 문제\n```\n"+nm
                            tierfind=problems["level"]#jsonData["result"]["problems"][0]["level"]
                            colorch=0
                            if tierfind==0:colorch=0
                            else:colorch=(tierfind-1)//5+1
                            nm+="난이도 : "+str(tier[tierfind])+"  "+tierimagelink[tierfind]+"\n\n"
                            nm+="tag : ||"
                            tagcnt=len(problems["tags"])
                            for i in range(tagcnt):
                                nm+=problems["tags"][i]["full_name_ko"]+"("+problems["tags"][i]["short_name_en"]+")"
                                if i+1!=tagcnt:nm+=", "
                            nm+="||\n\n"
                            url="https://www.acmicpc.net/problem/status/"+ex[1]
                            EM=discord.Embed(title=ex[1]+"번: "+problems["title"],description=nm,color=tiercolor[colorch])#0x62c1cc)
                            EM.set_author(name=message.author,icon_url=message.author.avatar_url)
                            EM.set_thumbnail(url=tierimagehtml[tierfind])
                            msg=await message.channel.send(embed=EM)
                        except:
                            await message.channel.send("문제 번호가 잘못되었습니다")
                        
                    elif qy[1]==1:
                        try:
                            qr=""
                            #print('https://solved.ac/profile/'+ex[2])
                            req1=requests.get('https://solved.ac/profile/'+ex[2])#https://solved.ac/profile/joseph0528
                            soup1=BeautifulSoup(req1.text, 'html.parser')
                            jsonData=json.loads(soup1.find('script', {'type':'application/json'}).string)['props']['pageProps']
                            psname=ex[2]
                            #print(psname)
                            qr+="**"+ex[2]+"**\n\n"#rank
                            qr+="랭킹 : "+str(jsonData["user"]["result"]["user"][0]["rank"])+"위\n\n"
                            #print('https://solved.ac/profile/'+ex[2])
                            tim=jsonData["user"]["result"]["user"][0]["level"]
                            if tim==0:colorch=0
                            else:colorch=(tim-1)//5+1
                            cl=jsonData["user"]["result"]["user"][0]["class"]
                            cld=jsonData["user"]["result"]["user"][0]["class_decoration"]
                            rating1=jsonData["user"]["result"]["user"][0]["rating"]
                            #print((cl-1)*3+cld+1,cl,cld)
                            qr+="티어 : "+tier[tim]+"   "+tierimagelink[tim]+"\n\n"
                            qr+="레이팅 : "+str(rating1)+"\n\n"
                            qr+="Class : "+str(cl)+"+"*(cld)+"  "+classimage[max(0,(cl-1)*3+cld+1)]+"\n\n"
                            qr+=qy[0]+"\n\n"
                            qr+="http://mazassumnida.wtf/api/v2/generate_badge?boj="+ex[2]
                            #print(tiercolor[colorch],colorch)
                            Embed=discord.Embed(title="",description=qr,color=tiercolor[colorch])
                            profileimage=jsonData["user"]["result"]["user"][0]["profile_image_url"]
                            #if ex[2]=="mjhmjh1104":
                            #    Embed.set_thumbnail(url="https://i.imgur.com/fjJbJ0T.png")
                            #    Embed.set_image(url="https://i.imgur.com/pGKiJ7o.png")
                            if profileimage==None:
                                Embed.set_thumbnail(url="https://media.discordapp.net/attachments/788579938239250462/807931237725241394/unknown.png")
                            else:
                                Embed.set_thumbnail(url=profileimage)
                            #tierimagelink[tim]
                            #if ex[2]!="mjhmjh1104":
                            #Embed.set_image(url=tierimagelink[tim])

                            msg=await message.channel.send(embed=Embed)
                        except:
                            await message.channel.send("유저 이름이 잘못되었습니다")
                    elif qy[1]==2:
                        return
                        qh=0
                        if len(ex)>=3:
                            qh=int(ex[2])
                            uy=chan(qh)
                            if uy[1]:
                                qh=1
                                await message.channel.send(uy[0])
                            else:
                                msg1=await message.channel.send(message.channel,embed=discord.Embed(title="",description=uy[0],color=0x62c1cc))
                                await msg1.edit(content="")
                                await msg1.add_reaction("\U00002B05")
                                await msg1.add_reaction("\U000027A1")
                        else:
                            qh=1
                            uy=chan(qh)
                            if uy[1]:
                                await message.channel.send(uy[0])
                            else:
                                msg1=await message.channel.send(message.channel,embed=discord.Embed(title="",description=uy[0],color=0x62c1cc))
                                await msg1.edit(content="")
                                await msg1.add_reaction("\U00002B05")
                                await msg1.add_reaction("\U000027A1")
                    else:
                        await message.channel.send(qy[0])
                else:
                    yu="이 기능을 사용하려면 아이디 추가를 해줘야합니다 아이디 추가하는 방법은 ~add 백준 닉네임 이렇게 치시면 됩니다."
                    await message.channel.send(yu)
                File.close()
      
    
@client.event
async def on_reaction_add(reaction,user):
    global qh,system,msg1,l,gp,gamescore,msg11,msg22
    if user.bot==1:return None
    #if str(reaction.emoji)=='👍':
    #    await reaction.message.channel.send(user)
    if str(reaction.emoji)=="\U00002B06":#up
        if gp==1 and player==str(user.id):
            #print("##")
            #await msg.delete()
            ch=[[0 for i in range(4)]for g in range(4)]
            for i in range(1,4):
                for g in range(4):
                    if l[i][g]!=0:
                        for t in range(i-1,-1,-1):
                            if l[t][g]==0:
                                l[t][g]=l[t+1][g]
                                l[t+1][g]=0
                            else:
                                if l[t][g]==l[t+1][g] and ch[t][g]==0:
                                    l[t][g]*=2
                                    gamescore+=l[t][g]
                                    l[t+1][g]=0
                                    ch[t][g]=1
                                break
            pr1=pt()
            #await msg.edit(content=pr1[0])
            #reaction.message.remove("\U00002B06")
            #await reaction.delete()
            msg111=msg11
            msg33=msg22
            msg22=await reaction.message.channel.send("**"+str(gamescore)+"점**\n")
            msg11=await reaction.message.channel.send(pr1[0])
            await msg11.add_reaction("\U00002B06")#up
            await msg11.add_reaction("\U00002B07")#down
            await msg11.add_reaction("\U00002B05")#left
            await msg11.add_reaction("\U000027A1")#right
            await msg111.delete()
            await msg33.delete()
            if pr1[1]==1:
                File=open('ranking.txt','a')
                print(str(user)+":"+str(gamescore)+"\n",file=File)
                File.close()
                Embed=discord.Embed(title="Game over",description="Your score is "+str(gamescore),color=0x62c1cc)
                await reactoin.message.channel.send(embed=Embed)
                gp=0

    if str(reaction.emoji)=="\U00002B07":#down
        if gp==1 and player==str(user.id):
            #print("##")
            #await msg.delete()
            ch=[[0 for i in range(4)]for g in range(4)]
            for i in range(2,-1,-1):
                for g in range(4):
                    if l[i][g]!=0:
                        for t in range(i+1,4):
                            if l[t][g]==0:
                                l[t][g]=l[t-1][g]
                                l[t-1][g]=0
                            else:
                                if l[t][g]==l[t-1][g] and ch[t][g]==0:
                                    l[t][g]*=2
                                    gamescore+=l[t][g]
                                    l[t-1][g]=0
                                    ch[t][g]=1
                                break
            pr1=pt()
            #await msg.edit(content=pr1[0])
            msg111=msg11
            msg33=msg22
            msg22=await reaction.message.channel.send("**"+str(gamescore)+"점**\n")
            msg11=await reaction.message.channel.send(pr1[0])
            await msg11.add_reaction("\U00002B06")#up
            await msg11.add_reaction("\U00002B07")#down
            await msg11.add_reaction("\U00002B05")#left
            await msg11.add_reaction("\U000027A1")#right
            await msg111.delete()
            await msg33.delete()
            if pr1[1]==1:
                File=open('ranking.txt','a')
                print(str(user)+":"+str(gamescore)+"\n",file=File)
                File.close()
                Embed=discord.Embed(title="Game over",description="Your score is "+str(gamescore),color=0x62c1cc)
                await reactoin.message.channel.send(embed=Embed)
                gp=0
    
    if str(reaction.emoji)=="\U000027A1":
        if gp==1 and player==str(user.id):
            #print("##")
            #await msg.delete()
            ch=[[0 for i in range(4)]for g in range(4)]
            for i in range(4):
                for g in range(2,-1,-1):
                    if l[i][g]!=0:
                        for t in range(g+1,4):
                            if l[i][t]==0:
                                l[i][t]=l[i][t-1]
                                l[i][t-1]=0
                            else:
                                if l[i][t]==l[i][t-1] and ch[i][t]==0:
                                    l[i][t]*=2
                                    gamescore+=l[i][t]
                                    l[i][t-1]=0
                                    ch[i][t]=1
                                break
            pr1=pt()
            msg111=msg11
            msg33=msg22
            #await msg.edit(content=pr1[0])
            msg22=await reaction.message.channel.send("**"+str(gamescore)+"점**\n")
            msg11=await reaction.message.channel.send(pr1[0])
            await msg11.add_reaction("\U00002B06")#up
            await msg11.add_reaction("\U00002B07")#down
            await msg11.add_reaction("\U00002B05")#left
            await msg11.add_reaction("\U000027A1")#right
            await msg111.delete()
            await msg33.delete()
            if pr1[1]==1:
                File=open('ranking.txt','a')
                print(str(user)+":"+str(gamescore)+"\n",file=File)
                File.close()
                Embed=discord.Embed(title="Game over",description="Your score is "+str(gamescore),color=0x62c1cc)
                await reactoin.message.channel.send(embed=Embed)
                gp=0
        else:
            qh+=1
            uy=chan(qh)
            if uy[1]:
                qh-=1
                await reaction.message.channel.send(uy[0])
            else:
                await msg1.delete()
                msg1=await reaction.message.channel.send(reaction.message.channel,embed=discord.Embed(title="",description=uy[0],color=0x62c1cc))
                await msg1.edit(content="")
                await msg1.add_reaction("\U00002B05")
                await msg1.add_reaction("\U000027A1")
    if str(reaction.emoji)=="\U00002B05":
        if gp==1 and player==str(user.id):
            #print("##")
            #await msg.delete()
            ch=[[0 for i in range(4)]for g in range(4)]
            for i in range(4):
                for g in range(1,4):
                    if l[i][g]!=0:
                        for t in range(g-1,-1,-1):
                            if l[i][t]==0:
                                l[i][t]=l[i][t+1]
                                l[i][t+1]=0
                            else:
                                if l[i][t]==l[i][t+1] and ch[i][t]==0:
                                    l[i][t]*=2
                                    gamescore+=l[i][t]
                                    l[i][t+1]=0
                                    ch[i][t]=1
                                break
            pr1=pt()
            msg111=msg11
            msg33=msg22
            #await msg.edit(content=pr1[0])
            msg22=await reaction.message.channel.send("**"+str(gamescore)+"점**\n")
            msg11=await reaction.message.channel.send(pr1[0])
            await msg11.add_reaction("\U00002B06")#up
            await msg11.add_reaction("\U00002B07")#down
            await msg11.add_reaction("\U00002B05")#left
            await msg11.add_reaction("\U000027A1")#right
            await msg111.delete()
            await msg33.delete()
            if pr1[1]==1:
                File=open('ranking.txt','a')
                print(str(user)+":"+str(gamescore)+"\n",file=File)
                File.close()
                Embed=discord.Embed(title="Game over",description="Your score is "+str(gamescore),color=0x62c1cc)
                await reaction.message.channel.send(embed=Embed)
                gp=0
        else:
            qh-=1
            qh=max(1,qh)
            uy=chan(qh)
            if uy[1]:
                qh+=1
                await reaction.message.channel.send(uy[0])
            else:
                await msg1.delete()
                msg1=await reaction.message.channel.send(reaction.message.channel,embed=discord.Embed(title="",description=uy[0],color=0x62c1cc))
                await msg1.edit(content="")
                await msg1.add_reaction("\U00002B05")
                await msg1.add_reaction("\U000027A1")      

 

어쩌다보니 코드가 좀 많이 길어졌다..

 

'개발' 카테고리의 다른 글

개발일지 1. 디스코드 봇 Solved_Coin 제작  (2) 2021.09.03
오랜만에 올리는 디코 봇 현황  (1) 2021.08.08
2048게임 제작  (5) 2021.02.28
디스코드 봇 업데이트  (0) 2021.02.08
디스코드 봇 개발  (1) 2021.01.25
댓글