feat: support reading config from environment variables

This commit is contained in:
hibobmaster 2023-04-10 21:40:39 +08:00
parent fb73d3e597
commit 1482e201a2
No known key found for this signature in database
GPG Key ID: 316B77D7914D713C
4 changed files with 50 additions and 29 deletions

View File

@ -1,3 +1,4 @@
# Please remove the option that is blank
HOMESERVER="https://matrix.xxxxxx.xxxx" # required
USER_ID="@lullap:xxxxxxxxxxxxx.xxx" # required
PASSWORD="xxxxxxxxxxxxxxx" # required

View File

@ -2,10 +2,10 @@
This is a simple Matrix bot that uses OpenAI's GPT API and Bing AI to generate responses to user inputs. The bot responds to four types of prompts: `!gpt`, `!chat` and `!bing` and `!pic` depending on the first word of the prompt.
![demo](https://i.imgur.com/kK4rnPf.jpeg "demo")
## Roadmap
1. Support reading config from environment variables
2. <del>Solve sync token persist problem when using access_token to login</del> Done!
3. <del>Support e2e session</del> Done!
## Feature
1. Support openai and Bing AI
2. Support Bing Image Creator
3. Support E2E Encrypted Room
## Installation and Setup
Docker method(Recommended):<br>
@ -18,9 +18,12 @@ sudo docker compose up -d
<hr>
To run this application, follow the steps below:<br>
1. Clone the repository:
1. Clone the repository and create virtual environment:
```
git clone https://github.com/hibobmaster/matrix_chatgpt_bot.git
python -m venv venv
source venv/bin/activate
```
2. Install the required dependencies:<br>
```

20
bot.py
View File

@ -527,14 +527,18 @@ class Bot:
# bot login
async def login(self) -> None:
try:
resp = await self.client.login(password=self.password)
if not isinstance(resp, LoginResponse):
logger.error("Login Failed")
print(f"Login Failed: {resp}")
sys.exit(1)
except Exception as e:
logger.error(f"Error: {e}", exc_info=True)
if self.access_token is not None:
logger.info("Login via access_token")
else:
logger.info("Login via password")
try:
resp = await self.client.login(password=self.password)
if not isinstance(resp, LoginResponse):
logger.error("Login Failed")
print(f"Login Failed: {resp}")
sys.exit(1)
except Exception as e:
logger.error(f"Error: {e}", exc_info=True)
# sync messages in the room
async def sync_forever(self, timeout=30000, full_state=True) -> None:

45
main.py
View File

@ -8,23 +8,36 @@ logger = getlogger()
async def main():
fp = open('config.json', 'r', encoding="utf8")
config = json.load(fp)
matrix_bot = Bot(homeserver=config.get('homeserver'),
user_id=config.get('user_id') ,
password=config.get('password'),
device_id=config.get('device_id'),
room_id=config.get('room_id'),
api_key=config.get('api_key'),
bing_api_endpoint=config.get('bing_api_endpoint'),
access_token=config.get('access_token'),
jailbreakEnabled=config.get('jailbreakEnabled'),
bing_auth_cookie=config.get('bing_auth_cookie'),
)
if os.path.exists('config.json'):
fp = open('config.json', 'r', encoding="utf8")
config = json.load(fp)
matrix_bot = Bot(homeserver=config.get('homeserver'),
user_id=config.get('user_id') ,
password=config.get('password'),
device_id=config.get('device_id'),
room_id=config.get('room_id'),
api_key=config.get('api_key'),
bing_api_endpoint=config.get('bing_api_endpoint'),
access_token=config.get('access_token'),
jailbreakEnabled=config.get('jailbreakEnabled'),
bing_auth_cookie=config.get('bing_auth_cookie'),
)
else:
matrix_bot = Bot(homeserver=os.environ.get('HOMESERVER'),
user_id=os.environ.get('USER_ID') ,
password=os.environ.get('PASSWORD'),
device_id=os.environ.get("DEVICE_ID"),
room_id=os.environ.get("ROOM_ID"),
api_key=os.environ.get("OPENAI_API_KEY"),
bing_api_endpoint=os.environ.get("BING_API_ENDPOINT"),
access_token=os.environ.get("ACCESS_TOKEN"),
jailbreakEnabled=os.environ.get("JAILBREAKENABLED"),
bing_auth_cookie=os.environ.get("BING_AUTH_COOKIE"),
)
await matrix_bot.login()
await matrix_bot.sync_encryption_key()
# await matrix_bot.trust_own_devices()
@ -33,7 +46,7 @@ async def main():
if __name__ == "__main__":
print("matrix chatgpt bot start.....")
logger.info("matrix chatgpt bot start.....")
asyncio.run(main())