資訊之芽 2022 Python 語法班
Author: Sean 韋詠祥
discord.py
pip3 install discord.py
Discord.py
QuickStartdiscord.errors.HTTPException: 401 Unauthorized
Traceback (most recent call last):
File "bot.py", line 17, in <module>
client.run('your token here')
File "site-packages/discord/client.py"
await self.login(*args, bot=bot)
discord.errors.LoginFailure: Improper token has been passed.
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('!ping'): await message.channel.send('Nice to meet you!') client.run('OTgy....xzfU')
name = 'Sean'
time = '14:30'
# 基本用法
print('Hey ' + name + ', it\'s ' + time + ' now.')
# 格式化文字
print(f'Hey {name}, it\'s {time} now.')
# 用 'string'.format(...) 處理格式化
print('Hey {}, it\'s {} now.'.format(name, time))
# 如果想指定變數順序呢?
print('{1}: Hey {0}, how are you?'.format(name, time))
# 讓我們再看一次前面的例子
print('We have logged in as {0.user}'.format(client))
pip3 install python-dotenv
from os import getenv
from dotenv import load_dotenv
load_dotenv()
TOKEN = getenv('TOKEN')
import discord from os import getenv from dotenv import load_dotenv # Load TOKEN from .env file load_dotenv() TOKEN = getenv('TOKEN') # Initial our bot client 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 # Ignore messages from myself, prevent loop # In this example, we use ! as command prefix if message.content.startswith('!ping'): await message.channel.send('Hey there!') # Must after all functions client.run(TOKEN)
if message.content.startswith('$play'):
await client.change_presence(
status=discord.Status.dnd,
activity=discord.Game(name="資訊之芽"))
await message.channel.send('I like playing!')
if message.content.startswith('!watch'):
await client.change_presence(
status=discord.Status.idle,
activity=discord.Activity(
type=discord.ActivityType.watching,
name="Apple 發表會"))
請參考 ActivityType
下一堂課內容: