---
# System prepended metadata

title: Discord Bot講義-8
tags: [Discord Bot講義]

---

# Discord Bot講義-8

1. 使用Google AI Studio編寫AI對話程式
2. 製作AI Discord Bot

## 使用Google AI Studio編寫AI對話程式
為什麼不用Chat GPT的服務呢? 
因為Chat GPT提供的免費額度是有限的，而 Google 的免費服務提供在1分鐘內60次的提問

首先，使用Google個人帳戶登入[Google AI Studio](https://aistudio.google.com/app/apikey?hl=zh-tw)獲得金鑰

接著按照前面[IDE教學](https://hackmd.io/@AndrewCho365/S1yXoFC8C)安裝**google.generativeai**套件
安裝完成後輸入以下程式碼⬇️(記得將api_key替換成你自己的)
```py=
import google.generativeai as genai
import os

api_key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
message = "message"

genai.configure(api_key=api_key)
generation_config = {
    "temperature": 0.9,
    "top_p": 1,
    "top_k": 1,
    "max_output_tokens": 2048,
}

safety_settings = [
    {
        "category": "HARM_CATEGORY_HARASSMENT",
        "threshold": "BLOCK_NONE"
    },
    {
        "category": "HARM_CATEGORY_HATE_SPEECH",
        "threshold": "BLOCK_NONE"
    },
    {
        "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
        "threshold": "BLOCK_NONE"
    },
    {
        "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
        "threshold": "BLOCK_NONE"
    },
]

model = genai.GenerativeModel(model_name="gemini-1.5-pro",
                generation_config=generation_config,
                safety_settings=safety_settings)

chat = model.start_chat(history=[])

while True:
  message = input("message: ")
  if message == "stop":
    os._exit(0)
  else:
    response = chat.send_message(message)
    print(f"AI:{response.text}")
```
接著就可以輸入文字，送出後AI就會回答
可以輸入stop結束對話

## 製作AI Discord Bot
要製作AI機器人，必須要有一個輸入的地方，
但是使用指令聊天又很奇怪，
所以可以使用訊息偵測的方式，
為了不要影響伺服器原本的對話，
可以使用前綴詞的方式啟動AI，
例如在句子前方加入一個"!"驚嘆號，
並且用程式去除驚嘆號後再交給AI回答。

以下是AI機器人的程式碼⬇️
```py=
import discord
import google.generativeai as genai

bot = discord.Bot(intents=discord.Intents.all())

api_key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
message = "message"

genai.configure(api_key=api_key)
generation_config = {
    "temperature": 0.9,
    "top_p": 1,
    "top_k": 1,
    "max_output_tokens": 2048,
}

safety_settings = [
    {
        "category": "HARM_CATEGORY_HARASSMENT",
        "threshold": "BLOCK_NONE"
    },
    {
        "category": "HARM_CATEGORY_HATE_SPEECH",
        "threshold": "BLOCK_NONE"
    },
    {
        "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
        "threshold": "BLOCK_NONE"
    },
    {
        "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
        "threshold": "BLOCK_NONE"
    },
]

model = genai.GenerativeModel(model_name="gemini-1.5-pro",
                generation_config=generation_config,
                safety_settings=safety_settings)

chat = model.start_chat(history=[])

@bot.event
async def on_ready():
    print(f"「{bot.user}」已登入")

@bot.event
async def on_message(message):
    if message.author == bot.user:
        return

    if message.content.startswith("!") or message.content.startswith("！"):
        response = "ERROR"
        response = chat.send_message(message.content[1:])
        await message.channel.send(response.text)
                
                
bot.run("bot_token")
```

### 圖片判斷

如果想要更進一步加上圖片判斷的功能
需要先按照前面[IDE教學](https://hackmd.io/@AndrewCho365/S1yXoFC8C)安裝**pillow**套件
接著輸入以下程式碼⬇️
```py=
import discord
import google.generativeai as genai
import PIL.Image

bot = discord.Bot(intents=discord.Intents.all())

api_key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
message = "message"

genai.configure(api_key=api_key)
generation_config = {
    "temperature": 0.9,
    "top_p": 1,
    "top_k": 1,
    "max_output_tokens": 2048,
}

safety_settings = [
    {
        "category": "HARM_CATEGORY_HARASSMENT",
        "threshold": "BLOCK_NONE"
    },
    {
        "category": "HARM_CATEGORY_HATE_SPEECH",
        "threshold": "BLOCK_NONE"
    },
    {
        "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
        "threshold": "BLOCK_NONE"
    },
    {
        "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
        "threshold": "BLOCK_NONE"
    },
]

model = genai.GenerativeModel(model_name="gemini-1.5-pro",
                generation_config=generation_config,
                safety_settings=safety_settings)

chat = model.start_chat(history=[])

@bot.event
async def on_ready():
    print(f"「{bot.user}」已登入")

@bot.event
async def on_message(message):
    if message.author == bot.user:
        return

    if message.content.startswith("!") or message.content.startswith("！"):
        response = "ERROR"
        img = None
        for attachment in message.attachments:
                    try:
                        img = PIL.Image.open(requests.get(attachment.url, stream=True).raw)
                    except Exception as e:
                        print(f"Error processing image: {e}")
                        await message.channel.send("I couldn't understand that image.")
        if img is not None:
            response = model.generate_content([f"{message.content[1:]}(盡量使用繁體中文輸出)", img])
        else:
            response = chat.send_message(message.content[1:])
        await message.channel.send(response.text)
                
                
bot.run("bot_token")
```
接著就可以在輸入文字時附上圖片，送出後AI就會回答圖片的內容

### 對話設定

如果你想要設定機器人回答的語言、風格或其他規定時
你可以在啟動時設定

例如使用以下程式碼⬇️

```PY=
@bot.event
async def on_ready():
    activity = discord.Activity(
                type=discord.ActivityType.playing,  
                name="/help"  
    )
    await bot.change_presence(activity=activity)
    print(f"「{bot.user}」已登入\n")

    update_channel_name_time.start()

    print("update_channel_name_time 已啟動")

    response = chat.send_message("你是一台Discord AI機器人，你有一些設定，請勿違反規定"
                                 "如果沒有特殊要求，請使用繁體中文作為輸出文字"
                                 "如果有人問你是誰，以完整的句子告訴他你的名字叫'XXX',並加上一些自我介紹。"
                                 "盡量適當的用表情符號表達情緒"
                                 "確認此設定後只需要輸出'設定完畢'。"
                                 "以上加上引號的文字輸出前後不可以加入任何文字。")
    print(response.text)
```