繼續測試前,一樣先沿用最簡單的範例,新增接接收訊息、收影像跟傳送影像這三個功能。
參考以下程式。
import discord
from discord.ext import commands
import urllib.request
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix = "%", intents = intents)
@bot.event
async def on_ready():
print(f"目前登入身份 --> {bot.user}")
@bot.command()
async def Hello(ctx):
await ctx.send("Hello, world!")
@bot.command()
async def Echo(ctx):
message = ' '.join(str(ctx.message.content).split(' ')[1:])
await ctx.send(message)
@bot.command()
async def getImg(ctx):
with open('testImg.png', 'rb') as f:
img = discord.File(f)
await ctx.send(file=img)
@bot.command()
async def sendImg(ctx):
request = urllib.request.Request(ctx.message.attachments[0].url)
request.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64)')
content = urllib.request.urlopen(request).read()
output = open(f"{ctx.message.author.id}.png", "wb")
output.write(content)
output.close()
await ctx.send("work")
bot.run("your discord token")
結果:
接下來串串 Gemini,照之前的方式處理環境、設定、提問的方式等可以參考 Day 3。
其他參考以下程式。
import google.generativeai as genai
import discord
from discord.ext import commands
import urllib.request
import PIL.Image
genai.configure(api_key = 'your Gemini token')
model = genai.GenerativeModel('gemini-1.5-flash')
cacheChat = {}
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix = "%", intents = intents)
@bot.event
async def on_ready():
print(f"目前登入身份 --> {bot.user}")
@bot.command()
async def Hello(ctx):
await ctx.send(f"Hello, {ctx.message.author.global_name}({ctx.message.author.name}).")
@bot.command()
async def magicConch(ctx):
global cacheChat
message = ' '.join(str(ctx.message.content).split(' ')[1:])
if ctx.message.author.id not in cacheChat.keys():
cacheChat[ctx.message.author.id] = model.start_chat(history = [])
response = cacheChat[ctx.message.author.id].send_message(message, stream = True)
for chunk in response:
await ctx.send(chunk.text)
@bot.command()
async def isThisPigeon(ctx):
request = urllib.request.Request(ctx.message.attachments[0].url)
request.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64)')
content = urllib.request.urlopen(request).read()
output = open(f"{ctx.message.author.id}.png", "wb")
output.write(content)
output.close()
image = PIL.Image.open(f'{ctx.message.author.id}.png')
message = ' '.join(str(ctx.message.content).split(' ')[1:])
if(len(message) == 0):
response = model.generate_content(image)
else:
response = model.generate_content([message, image])
embed = discord.Embed(title = f"Gemini", description = f"{response.text}")
await ctx.send(embed = embed)
bot.run("your discord token")
結果:
阿財鍋貼在台北,也沒看到有賣麵,老牌張豬腳賣的是豬腳飯,也沒有麵線或酸辣湯,已讀亂回耶 Gemini。
回覆影像相對正常不少。