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
Signed by: bobmaster
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 HOMESERVER="https://matrix.xxxxxx.xxxx" # required
USER_ID="@lullap:xxxxxxxxxxxxx.xxx" # required USER_ID="@lullap:xxxxxxxxxxxxx.xxx" # required
PASSWORD="xxxxxxxxxxxxxxx" # 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. 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") ![demo](https://i.imgur.com/kK4rnPf.jpeg "demo")
## Roadmap ## Feature
1. Support reading config from environment variables 1. Support openai and Bing AI
2. <del>Solve sync token persist problem when using access_token to login</del> Done! 2. Support Bing Image Creator
3. <del>Support e2e session</del> Done! 3. Support E2E Encrypted Room
## Installation and Setup ## Installation and Setup
Docker method(Recommended):<br> Docker method(Recommended):<br>
@ -18,9 +18,12 @@ sudo docker compose up -d
<hr> <hr>
To run this application, follow the steps below:<br> 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 git clone https://github.com/hibobmaster/matrix_chatgpt_bot.git
python -m venv venv
source venv/bin/activate
``` ```
2. Install the required dependencies:<br> 2. Install the required dependencies:<br>
``` ```

20
bot.py
View file

@ -527,14 +527,18 @@ class Bot:
# bot login # bot login
async def login(self) -> None: async def login(self) -> None:
try: if self.access_token is not None:
resp = await self.client.login(password=self.password) logger.info("Login via access_token")
if not isinstance(resp, LoginResponse): else:
logger.error("Login Failed") logger.info("Login via password")
print(f"Login Failed: {resp}") try:
sys.exit(1) resp = await self.client.login(password=self.password)
except Exception as e: if not isinstance(resp, LoginResponse):
logger.error(f"Error: {e}", exc_info=True) 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 # sync messages in the room
async def sync_forever(self, timeout=30000, full_state=True) -> None: 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(): async def main():
fp = open('config.json', 'r', encoding="utf8") if os.path.exists('config.json'):
config = json.load(fp) fp = open('config.json', 'r', encoding="utf8")
config = json.load(fp)
matrix_bot = Bot(homeserver=config.get('homeserver'),
user_id=config.get('user_id') , matrix_bot = Bot(homeserver=config.get('homeserver'),
password=config.get('password'), user_id=config.get('user_id') ,
device_id=config.get('device_id'), password=config.get('password'),
room_id=config.get('room_id'), device_id=config.get('device_id'),
api_key=config.get('api_key'), room_id=config.get('room_id'),
bing_api_endpoint=config.get('bing_api_endpoint'), api_key=config.get('api_key'),
access_token=config.get('access_token'), bing_api_endpoint=config.get('bing_api_endpoint'),
jailbreakEnabled=config.get('jailbreakEnabled'), access_token=config.get('access_token'),
bing_auth_cookie=config.get('bing_auth_cookie'), 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.login()
await matrix_bot.sync_encryption_key() await matrix_bot.sync_encryption_key()
# await matrix_bot.trust_own_devices() # await matrix_bot.trust_own_devices()
@ -33,7 +46,7 @@ async def main():
if __name__ == "__main__": if __name__ == "__main__":
print("matrix chatgpt bot start.....") logger.info("matrix chatgpt bot start.....")
asyncio.run(main()) asyncio.run(main())