__init__.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. from quora.api import Client as PoeClient
  2. from quora.mail import Mail
  3. from requests import Session
  4. from re import search, findall
  5. from json import loads
  6. from time import sleep
  7. from pathlib import Path
  8. from random import choice, choices, randint
  9. from string import ascii_letters, digits
  10. from urllib import parse
  11. from os import urandom
  12. from hashlib import md5
  13. from json import dumps
  14. from pypasser import reCaptchaV3
  15. def extract_formkey(html):
  16. script_regex = r'<script>if\(.+\)throw new Error;(.+)</script>'
  17. script_text = search(script_regex, html).group(1)
  18. key_regex = r'var .="([0-9a-f]+)",'
  19. key_text = search(key_regex, script_text).group(1)
  20. cipher_regex = r'.\[(\d+)\]=.\[(\d+)\]'
  21. cipher_pairs = findall(cipher_regex, script_text)
  22. formkey_list = [""] * len(cipher_pairs)
  23. for pair in cipher_pairs:
  24. formkey_index, key_index = map(int, pair)
  25. formkey_list[formkey_index] = key_text[key_index]
  26. formkey = "".join(formkey_list)
  27. return formkey
  28. class PoeResponse:
  29. class Completion:
  30. class Choices:
  31. def __init__(self, choice: dict) -> None:
  32. self.text = choice['text']
  33. self.content = self.text.encode()
  34. self.index = choice['index']
  35. self.logprobs = choice['logprobs']
  36. self.finish_reason = choice['finish_reason']
  37. def __repr__(self) -> str:
  38. return f'''<__main__.APIResponse.Completion.Choices(\n text = {self.text.encode()},\n index = {self.index},\n logprobs = {self.logprobs},\n finish_reason = {self.finish_reason})object at 0x1337>'''
  39. def __init__(self, choices: dict) -> None:
  40. self.choices = [self.Choices(choice) for choice in choices]
  41. class Usage:
  42. def __init__(self, usage_dict: dict) -> None:
  43. self.prompt_tokens = usage_dict['prompt_tokens']
  44. self.completion_tokens = usage_dict['completion_tokens']
  45. self.total_tokens = usage_dict['total_tokens']
  46. def __repr__(self):
  47. return f'''<__main__.APIResponse.Usage(\n prompt_tokens = {self.prompt_tokens},\n completion_tokens = {self.completion_tokens},\n total_tokens = {self.total_tokens})object at 0x1337>'''
  48. def __init__(self, response_dict: dict) -> None:
  49. self.response_dict = response_dict
  50. self.id = response_dict['id']
  51. self.object = response_dict['object']
  52. self.created = response_dict['created']
  53. self.model = response_dict['model']
  54. self.completion = self.Completion(response_dict['choices'])
  55. self.usage = self.Usage(response_dict['usage'])
  56. def json(self) -> dict:
  57. return self.response_dict
  58. class ModelResponse:
  59. def __init__(self, json_response: dict) -> None:
  60. self.id = json_response['data']['poeBotCreate']['bot']['id']
  61. self.name = json_response['data']['poeBotCreate']['bot']['displayName']
  62. self.limit = json_response['data']['poeBotCreate']['bot']['messageLimit']['dailyLimit']
  63. self.deleted = json_response['data']['poeBotCreate']['bot']['deletionState']
  64. class Model:
  65. def create(
  66. token: str,
  67. model: str = 'gpt-3.5-turbo', # claude-instant
  68. system_prompt: str = 'You are ChatGPT a large language model developed by Openai. Answer as consisely as possible',
  69. description: str = 'gpt-3.5 language model from openai, skidded by poe.com',
  70. handle: str = None) -> ModelResponse:
  71. models = {
  72. 'gpt-3.5-turbo' : 'chinchilla',
  73. 'claude-instant-v1.0': 'a2',
  74. 'gpt-4': 'beaver'
  75. }
  76. if not handle:
  77. handle = f'gptx{randint(1111111, 9999999)}'
  78. client = Session()
  79. client.cookies['p-b'] = token
  80. formkey = extract_formkey(client.get('https://poe.com').text)
  81. settings = client.get('https://poe.com/api/settings').json()
  82. client.headers = {
  83. "host" : "poe.com",
  84. "origin" : "https://poe.com",
  85. "referer" : "https://poe.com/",
  86. "content-type" : "application/json",
  87. "poe-formkey" : formkey,
  88. "poe-tchannel" : settings['tchannelData']['channel'],
  89. "user-agent" : "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36",
  90. "connection" : "keep-alive",
  91. "sec-ch-ua" : "\"Chromium\";v=\"112\", \"Google Chrome\";v=\"112\", \"Not:A-Brand\";v=\"99\"",
  92. "sec-ch-ua-mobile" : "?0",
  93. "sec-ch-ua-platform": "\"macOS\"",
  94. "content-type" : "application/json",
  95. "sec-fetch-site" : "same-origin",
  96. "sec-fetch-mode" : "cors",
  97. "sec-fetch-dest" : "empty",
  98. "accept" : "*/*",
  99. "accept-encoding" : "gzip, deflate, br",
  100. "accept-language" : "en-GB,en-US;q=0.9,en;q=0.8",
  101. }
  102. payload = dumps(separators=(',', ':'), obj = {
  103. 'queryName': 'CreateBotMain_poeBotCreate_Mutation',
  104. 'variables': {
  105. 'model' : models[model],
  106. 'handle' : handle,
  107. 'prompt' : system_prompt,
  108. 'isPromptPublic' : True,
  109. 'introduction' : '',
  110. 'description' : description,
  111. 'profilePictureUrl' : 'https://qph.fs.quoracdn.net/main-qimg-24e0b480dcd946e1cc6728802c5128b6',
  112. 'apiUrl' : None,
  113. 'apiKey' : ''.join(choices(ascii_letters + digits, k = 32)),
  114. 'isApiBot' : False,
  115. 'hasLinkification' : False,
  116. 'hasMarkdownRendering' : False,
  117. 'hasSuggestedReplies' : False,
  118. 'isPrivateBot' : False
  119. },
  120. 'query': 'mutation CreateBotMain_poeBotCreate_Mutation(\n $model: String!\n $handle: String!\n $prompt: String!\n $isPromptPublic: Boolean!\n $introduction: String!\n $description: String!\n $profilePictureUrl: String\n $apiUrl: String\n $apiKey: String\n $isApiBot: Boolean\n $hasLinkification: Boolean\n $hasMarkdownRendering: Boolean\n $hasSuggestedReplies: Boolean\n $isPrivateBot: Boolean\n) {\n poeBotCreate(model: $model, handle: $handle, promptPlaintext: $prompt, isPromptPublic: $isPromptPublic, introduction: $introduction, description: $description, profilePicture: $profilePictureUrl, apiUrl: $apiUrl, apiKey: $apiKey, isApiBot: $isApiBot, hasLinkification: $hasLinkification, hasMarkdownRendering: $hasMarkdownRendering, hasSuggestedReplies: $hasSuggestedReplies, isPrivateBot: $isPrivateBot) {\n status\n bot {\n id\n ...BotHeader_bot\n }\n }\n}\n\nfragment BotHeader_bot on Bot {\n displayName\n messageLimit {\n dailyLimit\n }\n ...BotImage_bot\n ...BotLink_bot\n ...IdAnnotation_node\n ...botHelpers_useViewerCanAccessPrivateBot\n ...botHelpers_useDeletion_bot\n}\n\nfragment BotImage_bot on Bot {\n displayName\n ...botHelpers_useDeletion_bot\n ...BotImage_useProfileImage_bot\n}\n\nfragment BotImage_useProfileImage_bot on Bot {\n image {\n __typename\n ... on LocalBotImage {\n localName\n }\n ... on UrlBotImage {\n url\n }\n }\n ...botHelpers_useDeletion_bot\n}\n\nfragment BotLink_bot on Bot {\n displayName\n}\n\nfragment IdAnnotation_node on Node {\n __isNode: __typename\n id\n}\n\nfragment botHelpers_useDeletion_bot on Bot {\n deletionState\n}\n\nfragment botHelpers_useViewerCanAccessPrivateBot on Bot {\n isPrivateBot\n viewerIsCreator\n}\n',
  121. })
  122. base_string = payload + client.headers["poe-formkey"] + 'WpuLMiXEKKE98j56k'
  123. client.headers["poe-tag-id"] = md5(base_string.encode()).hexdigest()
  124. response = client.post("https://poe.com/api/gql_POST", data = payload)
  125. if not 'success' in response.text:
  126. raise Exception('''
  127. Bot creation Failed
  128. !! Important !!
  129. Bot creation was not enabled on this account
  130. please use: quora.Account.create with enable_bot_creation set to True
  131. ''')
  132. return ModelResponse(response.json())
  133. class Account:
  134. def create(proxy: None or str = None, logging: bool = False, enable_bot_creation: bool = False):
  135. client = Session()
  136. client.proxies = {
  137. 'http': f'http://{proxy}',
  138. 'https': f'http://{proxy}'} if proxy else None
  139. mail = Mail(client.proxies)
  140. mail_token = None
  141. _, mail_address = mail.get_mail()
  142. if mail_address is None:
  143. raise Exception('Error creating mail, please use proxies')
  144. if logging: print('email', mail_address)
  145. client.headers = {
  146. "host" : "poe.com",
  147. "connection" : "keep-alive",
  148. "cache-control" : "max-age=0",
  149. "sec-ch-ua" : "\"Microsoft Edge\";v=\"111\", \"Not(A:Brand\";v=\"8\", \"Chromium\";v=\"111\"",
  150. "sec-ch-ua-mobile" : "?0",
  151. "sec-ch-ua-platform": "\"macOS\"",
  152. "user-agent" : "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36 Edg/111.0.1661.54",
  153. "accept" : "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
  154. "sec-fetch-site" : "same-origin",
  155. "sec-fetch-mode" : "navigate",
  156. "content-type" : "application/json",
  157. "sec-fetch-user" : "?1",
  158. "sec-fetch-dest" : "document",
  159. "accept-encoding" : "gzip, deflate, br",
  160. "accept-language" : "en-GB,en;q=0.9,en-US;q=0.8",
  161. "upgrade-insecure-requests": "1",
  162. }
  163. client.headers["poe-formkey"] = extract_formkey(client.get('https://poe.com/login').text)
  164. client.headers["poe-tchannel"] = client.get('https://poe.com/api/settings').json()['tchannelData']['channel']
  165. token = reCaptchaV3('https://www.recaptcha.net/recaptcha/enterprise/anchor?ar=1&k=6LflhEElAAAAAI_ewVwRWI9hsyV4mbZnYAslSvlG&co=aHR0cHM6Ly9wb2UuY29tOjQ0Mw..&hl=en&v=vkGiR-M4noX1963Xi_DB0JeI&size=invisible&cb=hhps5wd06eue')
  166. payload = dumps(separators = (',', ':'), obj = {
  167. 'queryName': 'MainSignupLoginSection_sendVerificationCodeMutation_Mutation',
  168. 'variables': {
  169. 'emailAddress': mail_address,
  170. 'phoneNumber': None,
  171. 'recaptchaToken': token
  172. },
  173. 'query': 'mutation MainSignupLoginSection_sendVerificationCodeMutation_Mutation(\n $emailAddress: String\n $phoneNumber: String\n $recaptchaToken: String\n) {\n sendVerificationCode(verificationReason: login, emailAddress: $emailAddress, phoneNumber: $phoneNumber, recaptchaToken: $recaptchaToken) {\n status\n errorMessage\n }\n}\n',
  174. })
  175. base_string = payload + client.headers["poe-formkey"] + 'WpuLMiXEKKE98j56k'
  176. client.headers["poe-tag-id"] = md5(base_string.encode()).hexdigest()
  177. response = client.post('https://poe.com/api/gql_POST', data=payload)
  178. if 'Bad Request' in response.text:
  179. if logging: print('bad request, retrying...' , response.json())
  180. quit()
  181. if logging: print('send_code' ,response.json())
  182. while True:
  183. sleep(1)
  184. messages = mail.fetch_inbox()
  185. if len(messages["messages"]) > 0:
  186. email_content = mail.get_message_content(messages["messages"][0]["_id"])
  187. mail_token = findall(r';">(\d{6,7})</div>', email_content)[0]
  188. if mail_token:
  189. break
  190. if logging: print('code', mail_token)
  191. payload = dumps(separators = (',', ':'), obj={
  192. "queryName": "SignupOrLoginWithCodeSection_signupWithVerificationCodeMutation_Mutation",
  193. "variables": {
  194. "verificationCode" : mail_token,
  195. "emailAddress" : mail_address,
  196. "phoneNumber" : None
  197. },
  198. "query": "mutation SignupOrLoginWithCodeSection_signupWithVerificationCodeMutation_Mutation(\n $verificationCode: String!\n $emailAddress: String\n $phoneNumber: String\n) {\n signupWithVerificationCode(verificationCode: $verificationCode, emailAddress: $emailAddress, phoneNumber: $phoneNumber) {\n status\n errorMessage\n }\n}\n"
  199. })
  200. base_string = payload + client.headers["poe-formkey"] + 'WpuLMiXEKKE98j56k'
  201. client.headers["poe-tag-id"] = md5(base_string.encode()).hexdigest()
  202. response = client.post('https://poe.com/api/gql_POST', data = payload)
  203. if logging: print('verify_code', response.json())
  204. token = parse.unquote(client.cookies.get_dict()['p-b'])
  205. with open(Path(__file__).resolve().parent / 'cookies.txt', 'a') as f:
  206. f.write(f'{token}\n')
  207. if enable_bot_creation:
  208. payload = dumps(separators = (',', ':'), obj={
  209. "queryName": "UserProfileConfigurePreviewModal_markMultiplayerNuxCompleted_Mutation",
  210. "variables": {},
  211. "query": "mutation UserProfileConfigurePreviewModal_markMultiplayerNuxCompleted_Mutation {\n markMultiplayerNuxCompleted {\n viewer {\n hasCompletedMultiplayerNux\n id\n }\n }\n}\n"
  212. })
  213. base_string = payload + client.headers["poe-formkey"] + 'WpuLMiXEKKE98j56k'
  214. client.headers["poe-tag-id"] = md5(base_string.encode()).hexdigest()
  215. resp = client.post("https://poe.com/api/gql_POST", data = payload)
  216. if logging: print(resp.json())
  217. return token
  218. def get():
  219. cookies = open(Path(__file__).resolve().parent / 'cookies.txt', 'r').read().splitlines()
  220. return choice(cookies)
  221. class StreamingCompletion:
  222. def create(
  223. model : str = 'gpt-4',
  224. custom_model : bool = None,
  225. prompt: str = 'hello world',
  226. token : str = ''):
  227. models = {
  228. 'sage' : 'capybara',
  229. 'gpt-4' : 'beaver',
  230. 'claude-v1.2' : 'a2_2',
  231. 'claude-instant-v1.0' : 'a2',
  232. 'gpt-3.5-turbo' : 'chinchilla'
  233. }
  234. _model = models[model] if not custom_model else custom_model
  235. client = PoeClient(token)
  236. for chunk in client.send_message(_model, prompt):
  237. yield PoeResponse({
  238. 'id' : chunk["messageId"],
  239. 'object' : 'text_completion',
  240. 'created': chunk['creationTime'],
  241. 'model' : _model,
  242. 'choices': [{
  243. 'text' : chunk["text_new"],
  244. 'index' : 0,
  245. 'logprobs' : None,
  246. 'finish_reason' : 'stop'
  247. }],
  248. 'usage': {
  249. 'prompt_tokens' : len(prompt),
  250. 'completion_tokens' : len(chunk["text_new"]),
  251. 'total_tokens' : len(prompt) + len(chunk["text_new"])
  252. }
  253. })
  254. class Completion:
  255. def create(
  256. model : str = 'gpt-4',
  257. custom_model : str = None,
  258. prompt: str = 'hello world',
  259. token : str = ''):
  260. models = {
  261. 'sage' : 'capybara',
  262. 'gpt-4' : 'beaver',
  263. 'claude-v1.2' : 'a2_2',
  264. 'claude-instant-v1.0' : 'a2',
  265. 'gpt-3.5-turbo' : 'chinchilla'
  266. }
  267. _model = models[model] if not custom_model else custom_model
  268. client = PoeClient(token)
  269. for chunk in client.send_message(_model, prompt):
  270. pass
  271. return PoeResponse({
  272. 'id' : chunk["messageId"],
  273. 'object' : 'text_completion',
  274. 'created': chunk['creationTime'],
  275. 'model' : _model,
  276. 'choices': [{
  277. 'text' : chunk["text"],
  278. 'index' : 0,
  279. 'logprobs' : None,
  280. 'finish_reason' : 'stop'
  281. }],
  282. 'usage': {
  283. 'prompt_tokens' : len(prompt),
  284. 'completion_tokens' : len(chunk["text"]),
  285. 'total_tokens' : len(prompt) + len(chunk["text"])
  286. }
  287. })
粤ICP备19079148号