xia的小窩

一起來coding和碼字吧

0%

python-Discord-bot,從0開始到做出一個機器人系列-30

開始部屬

部署到網路上

點擊

登入後會看到這個畫面

點擊左上方的加號

進行第一次的線上coding

在main上輸入

1
import discord

等他運作完後……

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# main.py
# 記得將items.json上傳
from discord import embeds, member, message
from discord.ext import commands
# from alive import stay
import discord
import json

bot = commands.Bot(command_prefix="!")
with open('items.json', "r", encoding = "utf8") as file:
data = json.load(file)

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

@bot.command()
async def hello(ctx):
await ctx.send("hello")

# stay()
bot.run(data['token'])
# 測試用程式碼

示意圖

撰寫一個小網頁可以知道目前的狀況

使用Flask

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# alive.py
from flask import Flask
from threading import Thread

app = Flask(__name__)

@app.route('/')
def home():
return "Alive"

def run():
app.run(host = '0.0.0.0', port = 8080)

def stay():
stay = Thread(target = run)
stay.start()

示意圖

放在網路上

點我

按照步驟

將網址貼上去

回到Discord的整合

點擊建立webhook

點我,然後將剛才複製的webhook網址貼上去

這時候可以按一下send,看看是否有運作

2.0部分更改

這裡的話我有寫一個最基本的給大家使用replit-discord-bot-sample,底下也有教學,照貼就好了。

反正就新開一個,看你要不要連github,我是有連…不過感覺連不連都沒差,我是習慣本地端一個replit一個…
因為有的東西在replit沒辦法用,所以本地端可以不代表replit可以用,這點要注意一下。

然後我有寫新的discord bot,點我可以從這邊觀看程式碼,規模不大,頂多夠日常用…
replit有限制,cpu會爆…爆了會強制讓bot下線,下線之後你前面的指令也沒辦法執行。
差不多就這樣吧。
其實還有 /slash指令可以寫的,不過這邊主要是把之前2021iT鐵人賽的東西搬過來,那就不贅述了。