Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
TheExplainthis committed Feb 21, 2023
0 parents commit c14e184
Show file tree
Hide file tree
Showing 19 changed files with 550 additions and 0 deletions.
120 changes: 120 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
# Logs
.DS_Store
*/.DS_Store
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)
web_modules/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env
.env.test

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Next.js build output
.next
out

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*


9 changes: 9 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
FROM python:3.9-alpine


COPY ./ /DiscordBot
WORKDIR /DiscordBot

RUN pip3 install -r requirements.txt

CMD ["python3", "main.py"]
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 ExplainThis

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
1 change: 1 addition & 0 deletions Procfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
web: python main.py
Empty file added README.en.md
Empty file.
94 changes: 94 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# ChatGPT Discord Bot

中文 | [English](README.en.md)

[![license](https://img.shields.io/pypi/l/ansicolortags.svg)](LICENSE) [![Release](https://img.shields.io/github/v/release/TheExplainthis/ChatGPT-Discord-Bot)](https://github.com/TheExplainthis/ChatGPT-Discord-Bot/releases/)


ChatGPT 串接到 Discord 上面,使得團隊在協作、溝通、效率上都能夠快速的提升,根據下面的安裝步驟,你也能在自己的 Discord 當中去導入 ChatGPT。


## 介紹
在 Discord 裡的每個頻道中導入 ChatGPT Bot,只要在輸入框輸入 `/chat` 就會 有一個 `/chat message` 的關鍵字自動帶入,直接輸入文字即可與 ChatGPT 互動,如下圖所示:
![Demo](https://github.com/TheExplainthis/ChatGPT-Discord-Bot/blob/main/demo/chatgpt-discord-bot.gif)


## 安裝步驟
### Token 取得
- 取得 OpenAI 給的 API Token:
1. [OpenAI](https://beta.openai.com/) 平台中註冊/登入帳號
2. 右上方有一個頭像,點入後選擇 `View API keys`
3. 點選中間的 `Create new secret key`
- 注意:每隻 API 有免費額度,也有其限制,詳情請看 [OpenAI Pricing](https://openai.com/api/pricing/)
- 取得 Discord Token:
1. 登入 [Discord Developer](https://discord.com/developers/applications)
2. 創建機器人:
1. 進入左方 `Applications`
2. 點擊右上方 `New Application` 並輸入 Bot 的名稱 > 確認後進入新頁面。
3. 點擊左方 `Bot`
4. 點擊右方 `Add Bot`
5. 下方 `MESSAGE CONTENT INTENT` 需打開
6. 按下 `Save Change`
7. Token 在上方選擇 `View Token` 或已申請過則會是 `Reset Token` 的按鈕。
3. 設定 OAuth2
1. 點擊左欄 `OAuth2`
2. 點擊左欄 `URL Generator`
3. 右欄 `SCOPES` 選擇 `bot`、右欄下方 `BOT PERMISSIONS` 選擇 `Administrator`
4. 複製最下方網址到瀏覽器中
5. 選擇欲加入的伺服器
6. 按下 `繼續` > `授權`

### 專案設置
1. Fork Github 專案:
1. 註冊/登入 [GitHub](https://github.com/)
2. 進入 [ChatGPT-Discord-Bot](https://github.com/TheExplainthis/ChatGPT-Discord-Bot)
3. 點選 `Star` 支持開發者
4. 點選 `Fork` 複製全部的程式碼到自己的倉庫
2. 部署(免費空間):
1. 進入 [replit](https://replit.com/)
2. 點選 `Sign Up` 直接用 `Github` 帳號登入並授權 -> 按下 `Skip` 跳過初始化設定
3. 進入後中間主頁的部分點選 `Create` -> 跳出框,點選右上角 `Import from Github`
4. 若尚未加入 Github 倉庫,則點選連結 `Connect GitHub to import your private repos.` -> 勾選 `Only select repositories` -> 選擇 `ChatGPT-Discord-Bot`
5. 回到第四步,此時 `Github URL` 可以選擇 `ChatGPT-Discord-Bot` 專案 -> 點擊 `Import from Github`

### 專案執行
1. 環境變數設定
1. 接續上一步 `Import` 完成後在 `Replit` 的專案管理頁面左下方 `Tools` 點擊 `Secrets`
2. 右方按下 `Got it` 後,即可新增環境變數,需新增:
1. OpenAI API Token:
- key: `OPENAI_API`
- value: `[由上方步驟一取得] sk-FoXXXX`
2. 欲選擇的模型:
- key: `OPENAI_MODEL_ENGINE`
- value: `text-davinci-003`
3. ChatGPT 回傳的文字限制
- key: `OPENAI_MAX_TOKENS`
- value: `128`
4. Discord Token:
- key: `DISCORD_TOKEN`
- value: `[由上方步驟一取得] MTA3NXXX`
2. 開始執行
1. 點擊上方的 `Run`
2. 成功後右邊畫面會顯示 `Hello. I am alive!`,並將畫面中上方的**網址複製**下來,下一步驟會用到
- 注意:若一小時內沒有任何請求,則程式會中斷,因此需要下步驟
3. CronJob 定時發送請求
1. 註冊/登入 [cron-job.org](https://cron-job.org/en/)
2. 進入後面板右上方選擇 `CREATE CRONJOB`
3. `Title` 輸入 `ChatGPT-Discord-Bot`,網址輸入上一步驟的網址
4. 下方則每 `5 分鐘` 打一次
5. 按下 `CREATE`


## 指令
| 指令 | 別名 | 說明 |
| --- | ---- |----- |
| `文字生成` | `/chat` | 在輸入框直接輸入 `/chat` 會後綴 `message` 直接輸入文字,即可調用 ChatGPT 模型。|
| `刪除紀錄` | `/reset` | ChatGPT 會記住前十次的問答紀錄,調用此指令則會清除。|
|`圖像生成` | `/imagine` | 在輸入框輸入 `/imagine` 會後綴 `prompt` 直接輸入文字,會調用 DALL·E 2 模型,即可生成圖像。|


## 相關專案
- [chatGPT-discord-bot](https://github.com/Zero6992/chatGPT-discord-bot)

## 授權
[MIT](LICENSE)
9 changes: 9 additions & 0 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
version: "3"

services:
app:
container_name: discord-chatgpt-ai-assistant
build: .
restart: always
ports:
- "${APP_PORT}:${APP_PORT}"
67 changes: 67 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
from dotenv import load_dotenv
from flask import Flask, request, abort
from linebot import (
LineBotApi, WebhookHandler
)
from linebot.exceptions import (
InvalidSignatureError
)
from linebot.models import (
MessageEvent, TextMessage, TextSendMessage, ImageSendMessage
)
import os

from src.chatgpt import ChatGPT, DALLE
from src.models import OpenAIModel
from src.memory import Memory
from src.logger import logger

load_dotenv('.env')

app = Flask(__name__)
line_bot_api = LineBotApi(os.getenv('LINE_CHANNEL_ACCESS_TOKEN'))
handler = WebhookHandler(os.getenv('LINE_CHANNEL_SECRET'))

models = OpenAIModel(api_key=os.getenv('OPENAI_API'), model_engine=os.getenv('OPENAI_MODEL_ENGINE'), max_tokens=int(os.getenv('OPENAI_MAX_TOKENS')))

memory = Memory()
chatgpt = ChatGPT(models, memory)
dalle = DALLE(models)


@app.route("/callback", methods=['POST'])
def callback():
signature = request.headers['X-Line-Signature']
body = request.get_data(as_text=True)
app.logger.info("Request body: " + body)
try:
handler.handle(body, signature)
except InvalidSignatureError:
print("Invalid signature. Please check your channel access token/channel secret.")
abort(400)
return 'OK'


@handler.add(MessageEvent, message=TextMessage)
def handle_text_message(event):
user_id = event.source.user_id
text = event.message.text
logger.info(f'{user_id}: {text}')
if text.startswith('/imagine'):
response = dalle.generate(text[8:].strip())
msg = ImageSendMessage(
original_content_url=response,
preview_image_url=response
)
else:
response = chatgpt.get_response(user_id, text)
msg = TextSendMessage(text=response)

line_bot_api.reply_message(
event.reply_token,
msg
)


if __name__ == "__main__":
app.run()
5 changes: 5 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
openai==0.26.5
requests==2.28.2
line-bot-sdk==2.4.1
python-dotenv==0.21.1
Flask==2.2.3
1 change: 1 addition & 0 deletions runtime.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
python-3.9.16
Empty file added src/__init__.py
Empty file.
27 changes: 27 additions & 0 deletions src/chatgpt.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from src.models import ModelInterface
from src.memory import MemoryInterface


class ChatGPT:
def __init__(self, model: ModelInterface, memory: MemoryInterface = None):
self.model = model
self.memory = memory

def get_response(self, user_id: str, text: str) -> str:
prompt = text if self.memory is None else f'{self.memory.get(user_id)}\n\n{text}'
response = self.model.text_completion(f'{prompt} <|endoftext|>')
if self.memory is not None:
self.memory.append(user_id, prompt)
self.memory.append(user_id, response)
return response

def clean_history(self, user_id: str) -> None:
self.memory.remove(user_id)


class DALLE:
def __init__(self, model: ModelInterface):
self.model = model

def generate(self, text: str) -> str:
return self.model.image_generation(text)
Loading

0 comments on commit c14e184

Please sign in to comment.