Skip to content

Instantly share code, notes, and snippets.

@motyar
Created March 17, 2023 17:14
Show Gist options
  • Save motyar/298d5908e01ba511c5d9df28e131b5db to your computer and use it in GitHub Desktop.
Save motyar/298d5908e01ba511c5d9df28e131b5db to your computer and use it in GitHub Desktop.
import sleekxmpp
import requests
# Replace CHATGPT_API_KEY with your own ChatGPT API key
CHATGPT_API_KEY = 'YOUR_CHATGPT_API_KEY'
class ChatGptBot(sleekxmpp.ClientXMPP):
def __init__(self, jid, password):
sleekxmpp.ClientXMPP.__init__(self, jid, password)
self.add_event_handler('session_start', self.start)
def start(self, event):
self.send_presence()
self.get_roster()
self.add_event_handler('message', self.message)
def message(self, message):
if message['type'] in ('chat', 'normal'):
response = self.get_chatgpt_response(message['body'])
self.send_message(message['from'], response)
def get_chatgpt_response(self, message):
url = 'https://api.openai.com/v1/engine/davinci-codex/completions'
headers = {'Authorization': f'Bearer {CHATGPT_API_KEY}', 'Content-Type': 'application/json'}
payload = {
'prompt': message,
'max_tokens': 60,
'n': 1,
'stop': '\n',
}
response = requests.post(url, headers=headers, json=payload)
if response.status_code == 200:
result = response.json()
return result['choices'][0]['text']
else:
return 'Sorry, something went wrong. Please try again later.'
if __name__ == '__main__':
bot = ChatGptBot('username@yourdomain.com', 'password')
bot.connect()
bot.process(block=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment