iT邦幫忙

2021 iThome 鐵人賽

DAY 15
0
自我挑戰組

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

加上random與time模組,限制次數與時間的管理(1)

顯示出現在的時間

  • 使用datatime模組
from datetime import datetime

now = datetime.now()
date_time = now.strftime("%Y-%m-%d, %H:%M:%S")
print(date_time)
  • 為何使用datetime,datetime模組提供處理日期與時間的class,在支持日期時間、數學運算的同時,它的關注點在於更有效的解析其屬性用於格式化輸出與數據上的操作

將時間丟入Bot內

# cogs/Times.py
# 略
@commands.command(pass_context = True)@bot.command()
async def time(ctx):
    now = datetime.now()
    await ctx.send(now.strftime("%Y-%m-%d %H:%M:%S"))
    # 略

寫入random模組

  • 第一,我們將會使用到random模組
    不多說,直接上碼
# cogs/randomLucky.py
# 略
import random

lucky = ["lucky~~~", "not bad", "Soso", "green hat", 
"fuck your self"]

class randomLucky(Cog_Extension):   
    @commands.command(pass_context = True)
    async def rand(ctx):
        cat = random.randint(0, 4)
        await ctx.channel.send(lucky[int(cat)])

# 略

關於次數問題

  • 如果我只想要一人一天只能發送一次呢??
    我們要怎麼做?
    剛才使用的author可以來出來了~~

  • 建立名為match的json檔

{

}
  • 然後為了方便,一律寫進函式裡
# 寫在最下面
async def read_data():
    with open("match.json", "r") as file:
        users = json.load(file)
    return users 

# bot.run...
  • 這個函式可以讀取json檔(唯讀),所以我將他每個users的這個key回傳

  • 然後,要怎麼寫??


上一篇
發送圖片與添加元素
下一篇
加上random與time模組,限制次數與時間的管理(2)
系列文
Discord-bot,從0開始到做出一個機器人30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言