├── .gitignore
├── LICENSE
├── README.md
├── examples
├── bot_list.py
├── create_bot.py
├── message_history.py
├── parallel_messages.py
├── repeated_messages.py
├── send_message.py
├── temporary_message.py
└── use_3rd_party_bot.py
├── setup.py
└── src
└── poe
├── __init__.py
├── hashes.py
└── poe_graphql
├── __init__.py
└── queries.json
/.gitignore:
--------------------------------------------------------------------------------
1 | #github boilerplate .gitignore
2 | #https://raw.githubusercontent.com/github/gitignore/main/Python.gitignore
3 |
4 | /.vscode
5 | pyrightconfig.json
6 |
7 | # Byte-compiled / optimized / DLL files
8 | __pycache__/
9 | *.py[cod]
10 | *$py.class
11 |
12 | # C extensions
13 | *.so
14 |
15 | # Distribution / packaging
16 | .Python
17 | build/
18 | develop-eggs/
19 | dist/
20 | downloads/
21 | eggs/
22 | .eggs/
23 | lib/
24 | lib64/
25 | parts/
26 | sdist/
27 | var/
28 | wheels/
29 | share/python-wheels/
30 | *.egg-info/
31 | .installed.cfg
32 | *.egg
33 | MANIFEST
34 |
35 | # PyInstaller
36 | # Usually these files are written by a python script from a template
37 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
38 | *.manifest
39 | *.spec
40 |
41 | # Installer logs
42 | pip-log.txt
43 | pip-delete-this-directory.txt
44 |
45 | # Unit test / coverage reports
46 | htmlcov/
47 | .tox/
48 | .nox/
49 | .coverage
50 | .coverage.*
51 | .cache
52 | nosetests.xml
53 | coverage.xml
54 | *.cover
55 | *.py,cover
56 | .hypothesis/
57 | .pytest_cache/
58 | cover/
59 |
60 | # Translations
61 | *.mo
62 | *.pot
63 |
64 | # Django stuff:
65 | *.log
66 | local_settings.py
67 | db.sqlite3
68 | db.sqlite3-journal
69 |
70 | # Flask stuff:
71 | instance/
72 | .webassets-cache
73 |
74 | # Scrapy stuff:
75 | .scrapy
76 |
77 | # Sphinx documentation
78 | docs/_build/
79 |
80 | # PyBuilder
81 | .pybuilder/
82 | target/
83 |
84 | # Jupyter Notebook
85 | .ipynb_checkpoints
86 |
87 | # IPython
88 | profile_default/
89 | ipython_config.py
90 |
91 | # pyenv
92 | # For a library or package, you might want to ignore these files since the code is
93 | # intended to run in multiple environments; otherwise, check them in:
94 | # .python-version
95 |
96 | # pipenv
97 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
98 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
99 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
100 | # install all needed dependencies.
101 | #Pipfile.lock
102 |
103 | # poetry
104 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105 | # This is especially recommended for binary packages to ensure reproducibility, and is more
106 | # commonly ignored for libraries.
107 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108 | #poetry.lock
109 |
110 | # pdm
111 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
112 | #pdm.lock
113 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
114 | # in version control.
115 | # https://pdm.fming.dev/#use-with-ide
116 | .pdm.toml
117 |
118 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
119 | __pypackages__/
120 |
121 | # Celery stuff
122 | celerybeat-schedule
123 | celerybeat.pid
124 |
125 | # SageMath parsed files
126 | *.sage.py
127 |
128 | # Environments
129 | .env
130 | .venv
131 | env/
132 | venv/
133 | ENV/
134 | env.bak/
135 | venv.bak/
136 |
137 | # Spyder project settings
138 | .spyderproject
139 | .spyproject
140 |
141 | # Rope project settings
142 | .ropeproject
143 |
144 | # mkdocs documentation
145 | /site
146 |
147 | # mypy
148 | .mypy_cache/
149 | .dmypy.json
150 | dmypy.json
151 |
152 | # Pyre type checker
153 | .pyre/
154 |
155 | # pytype static type analyzer
156 | .pytype/
157 |
158 | # Cython debug symbols
159 | cython_debug/
160 |
161 | # PyCharm
162 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
163 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
164 | # and can be added to the global gitignore or merged into this file. For a more nuclear
165 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
166 | #.idea/
167 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Important:
2 |
3 | ## This project has been unmaintained for over a month and does not work. See [issue #231](https://github.com/ading2210/poe-api/issues/231) for more details.
4 |
5 | # Python Poe API
6 |
7 | [](https://pypi.org/project/poe-api/)
8 |
9 | This is a reverse engineered API wrapper for Quora's Poe, which allows you free access to OpenAI's ChatGPT and GPT-4, as well as Anthropic's Claude.
10 |
11 | ## Table of Contents:
12 | - [Features](#features)
13 | - [Installation](#installation)
14 | - [Documentation](#documentation)
15 | * [Finding Your Token](#finding-your-token)
16 | * [Using the Client](#using-the-client)
17 | + [Downloading the Available Bots](#downloading-the-available-bots)
18 | + [Using 3rd Party Bots](#using-3rd-party-bots)
19 | + [Creating New Bots](#creating-new-bots)
20 | + [Editing a Bot](#editing-a-bot)
21 | + [Sending Messages](#sending-messages)
22 | + [Clearing the Conversation Context](#clearing-the-conversation-context)
23 | + [Downloading Conversation History](#downloading-conversation-history)
24 | + [Deleting Messages](#deleting-messages)
25 | + [Purging a Conversation](#purging-a-conversation)
26 | + [Purging All Conversations](#purging-all-conversations)
27 | + [Getting the Remaining Messages](#getting-the-remaining-messages)
28 | * [Misc](#misc)
29 | + [Changing the Logging Level](#changing-the-logging-level)
30 | + [Setting a Custom User-Agent](#setting-a-custom-user-agent)
31 | + [Setting a Custom Device ID](#setting-a-custom-device-id)
32 | - [Copyright](#copyright)
33 | * [Copyright Notice](#copyright-notice)
34 |
35 | *Table of contents generated with [markdown-toc](http://ecotrust-canada.github.io/markdown-toc).*
36 |
37 | ## Features:
38 | - Log in with token
39 | - Proxy requests + websocket
40 | - Download bot list
41 | - Send messages
42 | - Stream bot responses
43 | - Clear conversation context
44 | - Download conversation history
45 | - Delete messages
46 | - Purge an entire conversation
47 | - Create custom bots
48 | - Edit your custom bots
49 | - Use pre-existing third party bots
50 |
51 | ## Installation:
52 | You can install this library by running the following command:
53 | ```
54 | pip3 install poe-api
55 | ```
56 | This library depends on `quickjs`, which does not have prebuilt binaries available for Python 3.11. Pip will attempt to compile it, but will fail if `python-dev` is not installed.
57 |
58 | On Linux, you can install it via the instructions listed here: https://stackoverflow.com/questions/21530577/fatal-error-python-h-no-such-file-or-directory
59 |
60 | On Windows and MacOS, `python-dev` should be included with your existing Python installation.
61 |
62 | ## Documentation:
63 | Examples can be found in the `/examples` directory. To run these examples, pass in your token as a command-line argument.
64 | ```
65 | python3 examples/temporary_message.py "TOKEN_HERE"
66 | ```
67 |
68 | ### Finding Your Token:
69 | Log into [Poe](https://poe.com) on any desktop web browser, then open your browser's developer tools (also known as "inspect") and look for the value of the `p-b` cookie in the following menus:
70 | - Chromium: Devtools > Application > Cookies > poe.com
71 | - Firefox: Devtools > Storage > Cookies
72 | - Safari: Devtools > Storage > Cookies
73 |
74 | Note that excessive usage of this library may lead to your account getting banned. It is recommended that you set your own rate limits, and that you use an alt account that you don't value. See [issue #118](https://github.com/ading2210/poe-api/issues/118) for more details. If your requests are infrequent, the risk for a ban is very low.
75 |
76 | ### Using the Client:
77 | To use this library, simply import `poe` and create a `poe.Client` instance. The Client class accepts the following arguments:
78 | - `token` - The token to use.
79 | - `proxy = None` - The proxy to use, in the format `protocol://host:port`. The `socks5h` protocol is recommended, as it also proxies the DNS queries.
80 | - `device_id = None` - The device ID to use. If this is not specified, it will be randomly generated and stored on the disk.
81 | - `headers = headers` - The headers to use. This defaults to the headers specified in `poe.headers`.
82 | - `client_identifier = client_identifier` - The client identifier that will be passed into the TLS client library. This defaults to the one specified in `poe.client_identifier`.
83 | - `formkey = None` - The formkey to use. Only supply this option if initializing the client without it fails. You can find this value by going into your browser's devtools, looking in the network tab for a `gql_POST` request, and taking the value of the `poe-formkey` request header. The formkey that you use must come from a browser that matches the headers that you've set in `poe.headers`. Keep in mind that the default browser is Chromium 112.
84 |
85 | Regular Example:
86 | ```python
87 | import poe
88 | client = poe.Client("TOKEN_HERE")
89 | ```
90 |
91 | Proxied Example:
92 | ```python
93 | import poe
94 | client = poe.Client("TOKEN_HERE", proxy="socks5h://178.62.100.151:59166")
95 | ```
96 |
97 | Note that the following examples assume `client` is the name of your `poe.Client` instance. If the token is invalid, a RuntimeError will be raised.
98 |
99 | #### Downloading the Available Bots:
100 | The client downloads all of the available bots upon initialization and stores them within `client.bots`. A dictionary that maps bot codenames to their display names can be found at `client.bot_names`. If you want to refresh these values, you can call `client.get_bots`. This function takes the following arguments:
101 | - `download_next_data = True` - Whether or not to re-download the `__NEXT_DATA__`, which is required if the bot list has changed.
102 |
103 | ```python
104 | print(json.dumps(client.bot_names, indent=2))
105 | """
106 | {
107 | "chinchilla": "ChatGPT",
108 | "a2": "Claude-instant",
109 | "capybara": "Assistant",
110 | "a2_100k": "Claude-instant-100k",
111 | "llama_2_7b_chat": "Llama-2-7b",
112 | "llama_2_13b_chat": "Llama-2-13b",
113 | "a2_2": "Claude-2-100k",
114 | "llama_2_70b_chat": "Llama-2-70b",
115 | "agouti": "ChatGPT-16k",
116 | "beaver": "GPT-4",
117 | "vizcacha": "GPT-4-32k",
118 | "acouchy": "Google-PaLM"
119 | }
120 | """
121 | ```
122 |
123 | Note that, on free accounts, Claude+ (a2_2) has a limit of 3 messages per day and GPT-4 (beaver) has a limit of 1 message per day. Claude-instant-100k (c2_100k) is completely inaccessible for free accounts. For all the other chatbots, there seems to be a rate limit of 10 messages per minute.
124 |
125 | #### Using 3rd Party Bots:
126 | To get a list of 3rd party bots, use `client.explore_bots`, which accepts the following arguments:
127 | - `end_cursor = None` - The cursor to use when fetching the list.
128 | - `count = 25` - The number of bots that is returned.
129 |
130 | The function will return a dict containing a list of bots and the cursor for the next page:
131 | ```python
132 | print(json.dumps(client.explore_bots(count=1), indent=2))
133 | """
134 | {
135 | "bots": [
136 | {
137 | "id": "Qm90OjEwMzI2MDI=",
138 | "displayName": "leocooks",
139 | "deletionState": "not_deleted",
140 | "image": {
141 | "__typename": "UrlBotImage",
142 | "url": "https://qph.cf2.quoracdn.net/main-thumb-pb-1032602-200-uorvomwowfgmatdvrtwajtwwqlujmmgu.jpeg"
143 | },
144 | "botId": 1032602,
145 | "followerCount": 1922,
146 | "description": "Above average meals for average cooks, made simple by world-renowned chef, Leonardo",
147 | "__typename": "Bot"
148 | }
149 | ],
150 | "end_cursor": "1000172"
151 | }
152 | """
153 | ```
154 |
155 | To get a specific third party bot, you can use `client.get_bot_by_codename`, which accept's the bot's codename as its only argument.
156 | ```python
157 | client.get_bot_by_codename("JapaneseTutor")
158 | ```
159 |
160 | Since display names are the same as the codenames for custom bots, you can simply pass the bot's display name into `client.send_message` to send it a message.
161 |
162 | #### Creating New Bots:
163 | You can create a new bot using the `client.create_bot` function, which accepts the following arguments:
164 | - `handle` - The handle of the new bot.
165 | - `prompt = ""` - The prompt for the new bot.
166 | - `display_name = None` - The display name for the new bot.
167 | - `base_model = "chinchilla"` - The model that the new bot uses. This must be either `"chinchilla"` (ChatGPT) or `"a2"` (Claude). If you've subscribed, you can use `"beaver"` (ChatGPT4) or "a2_2"` (Claude-2-100k).
168 | - `description = ""` - The description for the new bot.
169 | - `intro_message = ""` - The intro message for the new bot. If this is an empty string then the bot will not have an intro message.
170 | - `prompt_public = True` - Whether or not the prompt should be publicly visible.
171 | - `pfp_url = None` - The URL for the bot's profile picture. Currently, there is no way to actually upload a custom image using this library.
172 | - `linkification = False` - Whether or not the bot should turn some text in the response into clickable links.
173 | - `markdown_rendering = True` - Whether or not to enable markdown rendering for the bot's responses.
174 | - `suggested_replies = False` - Whether or not the bot should suggest possible replies after each response.
175 | - `private = False` - Whether or not the bot should be private.
176 | - `temperature = None`: - The temperature for the new bot.
177 |
178 | Use these arguments if you want the new bot to use your own API (as detailed [here](https://github.com/poe-platform/api-bot-tutorial)):
179 | - `api_key = None` - The API key for the new bot.
180 | - `api_bot = False` - Whether or not the bot has API functionally enabled.
181 | - `api_url = None` - The API URL for the new bot.
182 |
183 | A full example of how to create and edit bots is located at `examples/create_bot.py`.
184 | ```python
185 | new_bot = client.create_bot(bot_name, "prompt goes here", base_model="a2")
186 | ```
187 |
188 | #### Editing a Bot:
189 | You can edit a custom bot using the `client.edit_bot` function, which accepts the following arguments:
190 | - `bot_id` - The `botId` of the bot to edit. This can also be set to `None`.
191 | - `handle` - The handle for the bot you're editing.
192 | - `prompt` - The new prompt for the bot.
193 | - `new_handle = None` - The new handle for the bot. By default the handle will not change.
194 | - `display_name = None` - The new display name for the bot.
195 | - `base_model = "chinchilla"` - The new model that the bot uses. This must be either `"chinchilla"` (ChatGPT) or `"a2"` (Claude). If you've subscribed, you can use `"beaver"` (ChatGPT4) or "a2_2"` (Claude-2-100k).
196 | - `description = ""` - The new description for the bot.
197 | - `intro_message = ""` - The new intro message for the bot. If this is an empty string then the bot will not have an intro message.
198 | - `prompt_public = True` - Whether or not the prompt should be publicly visible.
199 | - `pfp_url = None` - The URL for the bot's profile picture. Currently, there is no way to actually upload a custom image using this library.
200 | - `linkification = False` - Whether or not the bot should turn some text in the response into clickable links.
201 | - `markdown_rendering = True` - Whether or not to enable markdown rendering for the bot's responses.
202 | - `suggested_replies = False` - Whether or not the bot should suggest possible replies after each response.
203 | - `private = False` - Whether or not the bot should be private.
204 | - `temperature = None`: - The new temperature for the this bot.
205 |
206 | Bot API related arguments:
207 | - `api_key = None` - The new API key for the bot.
208 | - `api_url = None` - The new API URL for the bot.
209 |
210 | A full example of how to create and edit bots is located at `examples/create_bot.py`.
211 | ```python
212 | edit_result = client.edit_bot(1086981, "bot_handle_here", base_model="a2")
213 | ```
214 |
215 | #### Sending Messages:
216 | You can use the `client.send_message` function to send a message to a chatbot, which accepts the following arguments:
217 | - `chatbot` - The codename of the chatbot. (example: `capybara`)
218 | - `message` - The message to send to the chatbot.
219 | - `with_chat_break = False` - Whether the conversation context should be cleared.
220 | - `timeout = 20` - The max number of seconds in between received chunks until a `RuntimeError` is raised.
221 | - `async_recv = True` - Whether or not to make the `receive_POST` request async. If this is disabled, then there will be an extra wait of about 3 seconds after the message is complete.
222 | - `suggest_callback = None` - Callback for suggested replies. See `examples/send_message.py` for an example on how to use this.
223 |
224 | The function is a generator which returns the most recent version of the generated message whenever it is updated.
225 |
226 | Streamed Example:
227 | ```python
228 | message = "Summarize the GNU GPL v3"
229 | for chunk in client.send_message("capybara", message):
230 | print(chunk["text_new"], end="", flush=True)
231 | ```
232 |
233 | Non-Streamed Example:
234 | ```python
235 | message = "Summarize the GNU GPL v3"
236 | for chunk in client.send_message("capybara", message):
237 | pass
238 | print(chunk["text"])
239 | ```
240 |
241 | You can also send multiple messages in parallel using `threading` and receive their responses separately, as demonstrated in `/examples/parallel_messages.py`. Note that if you send messages too fast, the server will give an error, but the request will eventually succeed.
242 |
243 | The `client.is_busy` function can be used to check if there is currently a message being received.
244 |
245 | #### Clearing the Conversation Context:
246 | If you want to clear the the context of a conversation without sending a message, you can use `client.send_chat_break`. The only argument is the codename of the bot whose context will be cleared.
247 |
248 | ```python
249 | client.send_chat_break("capybara")
250 | ```
251 | The function returns the message which represents the chat break.
252 |
253 | #### Downloading Conversation History:
254 | To download past messages in a conversation, use the `client.get_message_history` function, which accepts the following arguments:
255 | - `chatbot` - The codename of the chatbot.
256 | - `count = 25` - The number of messages to download.
257 | - `cursor = None` - The message ID to start at instead of the latest one.
258 |
259 | Note that if you don't specify a cursor, the client will have to perform an extra request to determine what the latest cursor is.
260 |
261 | The returned messages are ordered from oldest to newest.
262 |
263 | ```python
264 | message_history = client.get_message_history("capybara", count=10)
265 | print(json.dumps(message_history, indent=2))
266 | """
267 | [
268 | {
269 | "node": {
270 | "id": "TWVzc2FnZToxMDEwNzYyODU=",
271 | "messageId": 101076285,
272 | "creationTime": 1679298157718888,
273 | "text": "",
274 | "author": "chat_break",
275 | "linkifiedText": "",
276 | "state": "complete",
277 | "suggestedReplies": [],
278 | "vote": null,
279 | "voteReason": null,
280 | "__typename": "Message"
281 | },
282 | "cursor": "101076285",
283 | "id": "TWVzc2FnZUVkZ2U6MTAxMDc2Mjg1OjEwMTA3NjI4NQ=="
284 | },
285 | ...
286 | ]
287 | """
288 | ```
289 |
290 | #### Deleting Messages:
291 | To delete messages, use the `client.delete_message` function, which accepts a single argument. You can pass a single message ID into it to delete a single message, or you can pass a list of message IDs to delete multiple messages at once.
292 |
293 | ```python
294 | #delete a single message
295 | client.delete_message(96105719)
296 |
297 | #delete multiple messages at once
298 | client.delete_message([96105719, 96097108, 96097078, 96084421, 96084402])
299 | ```
300 |
301 | #### Purging a Conversation:
302 | To purge an entire conversation, or just the last few messages, you can use the `client.purge_conversation` function. This function accepts the following arguments:
303 | - `chatbot` - The codename of the chatbot.
304 | - `count = -1` - The number of messages to be deleted, starting from the latest one. The default behavior is to delete every single message.
305 |
306 | ```python
307 | #purge just the last 10 messages
308 | client.purge_conversation("capybara", count=10)
309 |
310 | #purge the entire conversation
311 | client.purge_conversation("capybara")
312 | ```
313 |
314 | #### Purging All Conversations:
315 | To purge every conversation in your account, use the `client.purge_all_conversations` function. This function doesn't need any arguments.
316 |
317 | ```python
318 | >>> client.purge_all_conversations()
319 | ```
320 |
321 | #### Getting the Remaining Messages:
322 | To get the number of messages remaining in the quota for a conversation, use the `client.get_remaining_messages` function. This function accepts the following arguments:
323 | - `chatbot` - The codename of the chatbot.
324 |
325 | The function will return the number of messages remaining, or `None` if the bot does not have a quota.
326 |
327 | ```python
328 | >>> client.get_remaining_messages("beaver")
329 | 1
330 | ```
331 |
332 | ### Misc:
333 | #### Changing the Logging Level:
334 | If you want to show debug messages, simply call `poe.logger.setLevel`.
335 |
336 | ```python
337 | import poe
338 | import logging
339 | poe.logger.setLevel(logging.INFO)
340 | ```
341 |
342 | #### Setting a Custom User-Agent:
343 | If you want to change the headers that are spoofed, set `poe.headers` after importing the library.
344 |
345 | To use your browser's own headers, visit [this site](https://headers.uniqueostrich18.repl.co/), and copy-paste its contents.
346 | ```python
347 | import poe
348 | poe.headers = {
349 | "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0",
350 | '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',
351 | "Accept-Encoding": "gzip, deflate, br",
352 | 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
353 | "Upgrade-Insecure-Requests": "1"
354 | }
355 | ```
356 |
357 | The following headers will be ignored and overwritten:
358 | ```python
359 | {
360 | "Referrer": "https://poe.com/",
361 | "Origin": "https://poe.com",
362 | "Host": "poe.com",
363 | "Cache-Control": "no-cache",
364 | "Sec-Fetch-Dest": "document",
365 | "Sec-Fetch-Mode": "navigate",
366 | "Sec-Fetch-Site": "same-origin",
367 | "Sec-Fetch-User": "?1",
368 | }
369 | ```
370 |
371 | Previously, this was done through `poe.user_agent`, but that variable is now completely ignored.
372 |
373 | You'd also want to change `poe.client_identifier` to match the user-agent that you have set. See the [Python-TLS-Client documentation](https://github.com/FlorianREGAZ/Python-Tls-Client#examples) for some sample values. Keep in mind that spoofing Chrome/Firefox versions >= 110 may be detectable.
374 | ```python
375 | poe.client_identifier = "chrome_107"
376 | ```
377 |
378 | ### Setting a Custom Device ID:
379 | If you want to change the device ID that is being spoofed, you can use the `poe.set_device_id`, which accepts the following arguments:
380 | - `user_id` - The user ID of the account you want to change the device ID for. The user ID can be found at `client.viewer["poeUser"]["id"]`.
381 | - `device_id` - The new device ID. This is a 32 character UUID string in the following format: `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`
382 |
383 | ```python
384 | poe.set_device_id("UGMlVXqlcLYyMOATMDsKNTMz", "6d659b04-043a-41f8-97c7-fb7d7fe9ad34")
385 | ```
386 |
387 | The device IDs are saved to `~/.config/poe-api/device_id.json` on Unix-like systems, and `C:\Users\\AppData\Roaming\poe-api\device_id.json` on Windows.
388 |
389 | Additionally, the `poe.get_device_id` function or `client.device_id` can be used to retrieve the saved device ID.
390 | ```python
391 | >>> poe.get_device_id("UGMlVXqlcLYyMOATMDsKNTMz")
392 | #6d659b04-043a-41f8-97c7-fb7d7fe9ad34
393 |
394 | >>> client.device_id
395 | #6d659b04-043a-41f8-97c7-fb7d7fe9ad34
396 | ```
397 |
398 | ## Copyright:
399 | This program is licensed under the [GNU GPL v3](https://www.gnu.org/licenses/gpl-3.0.txt). Most code, with the exception of the GraphQL queries, has been written by me, [ading2210](https://github.com/ading2210).
400 |
401 | Reverse engineering the `poe-tag-id` header has been done by [xtekky](https://github.com/xtekky) in [PR #39](https://github.com/ading2210/poe-api/pull/39).
402 |
403 | The `client.get_remaining_messages` function was written by [Snowad14](https://github.com/Snowad14) in [PR #46](https://github.com/ading2210/poe-api/pull/46).
404 |
405 | Detection avoidance and fetching the third party bots has been done by [acheong08](https://github.com/acheong08/) in [PR #79](https://github.com/ading2210/poe-api/pull/79).
406 |
407 | Most of the GraphQL queries are taken from [muharamdani/poe](https://github.com/muharamdani/poe), which is licensed under the ISC License.
408 |
409 | ### Copyright Notice:
410 | ```
411 | ading2210/poe-api: a reverse engineered Python API wrapper for Quora's Poe
412 | Copyright (C) 2023 ading2210
413 |
414 | This program is free software: you can redistribute it and/or modify
415 | it under the terms of the GNU General Public License as published by
416 | the Free Software Foundation, either version 3 of the License, or
417 | (at your option) any later version.
418 |
419 | This program is distributed in the hope that it will be useful,
420 | but WITHOUT ANY WARRANTY; without even the implied warranty of
421 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
422 | GNU General Public License for more details.
423 |
424 | You should have received a copy of the GNU General Public License
425 | along with this program. If not, see .
426 | ```
--------------------------------------------------------------------------------
/examples/bot_list.py:
--------------------------------------------------------------------------------
1 | import poe
2 | import logging
3 | import sys
4 | import json
5 |
6 | #get the account's bot list
7 |
8 | token = sys.argv[1]
9 | poe.logger.setLevel(logging.INFO)
10 | client = poe.Client(token)
11 |
12 | print(json.dumps(client.bot_names, indent=2))
--------------------------------------------------------------------------------
/examples/create_bot.py:
--------------------------------------------------------------------------------
1 | import poe
2 | import logging
3 | import sys
4 |
5 | #create a bot and edit its model
6 | poe.logger.setLevel(logging.INFO)
7 | token = sys.argv[1]
8 | client = poe.Client(token)
9 |
10 | bot_name = input("bot handle name: ")
11 | display_name = input("bot display name: ")
12 | prompt = input("bot prompt: ")
13 | new_bot = client.create_bot(
14 | bot_name,
15 | prompt,
16 | display_name=display_name,
17 | base_model="a2"
18 | )
19 | print("new bot created: " + bot_name)
20 |
21 | handle = bot_name.lower()
22 | bot_id = client.bots[handle]["defaultBotObject"]["botId"]
23 | edit_result = client.edit_bot(
24 | None, handle, prompt,
25 | base_model="chinchilla"
26 | ) #switch model to ChatGPT
27 |
28 | print("edit status: " + edit_result["status"])
29 |
30 |
--------------------------------------------------------------------------------
/examples/message_history.py:
--------------------------------------------------------------------------------
1 | import poe
2 | import logging
3 | import sys
4 |
5 | #fetch the last 10 messages in ChatGPT's conversation
6 |
7 | token = sys.argv[1]
8 | poe.logger.setLevel(logging.INFO)
9 | client = poe.Client(token)
10 |
11 | message_history = client.get_message_history("chinchilla", count=50)
12 | print(f"Last {len(message_history)} messages:")
13 | for message in message_history:
14 | node = message["node"]
15 | print(f'{node["author"]}: {node["text"]}')
--------------------------------------------------------------------------------
/examples/parallel_messages.py:
--------------------------------------------------------------------------------
1 | import poe
2 | import logging
3 | import sys
4 | import threading
5 | import time
6 |
7 | #send multiple messages and get their responses
8 | #note: this is not recommended anymore due to the risk of a ban
9 |
10 | token = sys.argv[1]
11 | poe.logger.setLevel(logging.INFO)
12 | client = poe.Client(token)
13 |
14 | thread_count = 0
15 |
16 | def message_thread(prompt, counter):
17 | global thread_count
18 | for chunk in client.send_message("capybara", prompt, with_chat_break=True):
19 | pass
20 | print(prompt+"\n"+chunk["text"]+"\n"*3)
21 | thread_count -= 1
22 |
23 | prompts = [
24 | "Write a paragraph about the impact of social media on mental health.",
25 | "Write a paragraph about the history and significance of the Olympic Games.",
26 | "Write a paragraph about the effects of climate change on the world's oceans.",
27 | "Write a paragraph about the benefits and drawbacks of remote work for employees and companies.",
28 | "Write a paragraph about the role of technology in modern education.",
29 | "Write a paragraph about the history and impact of the Civil Rights Movement in America.",
30 | "Write a paragraph about the impact of COVID-19 on global economies.",
31 | "Write a paragraph about the rise and fall of the Roman Empire.",
32 | "Write a paragraph about the benefits and drawbacks of genetically modified organisms (GMOs).",
33 | "Write a paragraph about the impact of globalization on cultural identity.",
34 | "Write a paragraph about the history and significance of the Mona Lisa painting.",
35 | "Write a paragraph about the benefits and drawbacks of renewable energy sources.",
36 | "Write a paragraph about the impact of social media on political discourse.",
37 | "Write a paragraph about the history and impact of the Industrial Revolution.",
38 | "Write a paragraph about the benefits and drawbacks of online shopping for consumers and businesses.",
39 | "Write a paragraph about the impact of artificial intelligence on the job market.",
40 | "Write a paragraph about the history and significance of the Great Wall of China.",
41 | "Write a paragraph about the benefits and drawbacks of standardized testing in schools.",
42 | "Write a paragraph about the impact of the feminist movement on women's rights.",
43 | "Write a paragraph about the history and impact of the American Revolution."
44 | ]
45 |
46 | for i in range(len(prompts)):
47 | t = threading.Thread(target=message_thread, args=(prompts[i], i), daemon=True)
48 | t.start()
49 | thread_count += 1
50 |
51 | while thread_count:
52 | time.sleep(0.1)
53 |
54 | client.purge_conversation("capybara")
--------------------------------------------------------------------------------
/examples/repeated_messages.py:
--------------------------------------------------------------------------------
1 | import poe
2 | import logging
3 | import sys
4 | import time
5 |
6 | #send messages in a loop
7 |
8 | poe.logger.setLevel(logging.INFO)
9 | token = sys.argv[1]
10 | client = poe.Client(token)
11 |
12 | message = "This is message number {num}."
13 |
14 | counter = 1
15 | while True:
16 | for chunk in client.send_message("capybara", message.format(num=counter), with_chat_break=True):
17 | print(chunk["text_new"], end="", flush=True)
18 | print()
19 | counter += 1
20 | time.sleep(2)
--------------------------------------------------------------------------------
/examples/send_message.py:
--------------------------------------------------------------------------------
1 | import poe
2 | import logging
3 | import sys
4 | import time
5 |
6 | #send a message and stream the response
7 |
8 | token = sys.argv[1]
9 | poe.logger.setLevel(logging.INFO)
10 | client = poe.Client(token)
11 |
12 | def callback(suggestion):
13 | print("Suggested reply:", suggestion)
14 |
15 | message = "Summarize the GNU GPL v3"
16 | for chunk in client.send_message("capybara", message, with_chat_break=True, suggest_callback=callback):
17 | print(chunk["text_new"], end="", flush=True)
18 | print()
19 |
20 | # Suggested replies usually come in a few seconds after the message is fully received
21 | time.sleep(5)
--------------------------------------------------------------------------------
/examples/temporary_message.py:
--------------------------------------------------------------------------------
1 | import poe
2 | import logging
3 | import sys
4 |
5 | #send a message and immediately delete it
6 |
7 | token = sys.argv[1]
8 | poe.logger.setLevel(logging.INFO)
9 | client = poe.Client(token)
10 |
11 | message = "Who are you?"
12 | for chunk in client.send_message("capybara", message, with_chat_break=True):
13 | print(chunk["text_new"], end="", flush=True)
14 |
15 | #delete the 3 latest messages, including the chat break
16 | client.purge_conversation("capybara", count=3)
--------------------------------------------------------------------------------
/examples/use_3rd_party_bot.py:
--------------------------------------------------------------------------------
1 | import poe
2 | import sys
3 | import logging
4 |
5 | #download a list of third party bots and send a message to one of them
6 |
7 | poe.logger.setLevel(logging.INFO)
8 | token = sys.argv[1]
9 | client = poe.Client(token)
10 |
11 | bots = client.explore_bots()
12 | bots = client.explore_bots(end_cursor=bots["end_cursor"])
13 |
14 | bot = bots["bots"][-1]
15 | bot_name = bot.get("displayName")
16 | bot_id = bot.get("botId")
17 |
18 | print(f"Bot name: {bot_name}")
19 |
20 | message = "Summarize the GNU GPL v3"
21 | for chunk in client.send_message(bots["bots"][-1].get("displayName"), message, with_chat_break=True):
22 | print(chunk["text_new"], end="", flush=True)
23 | print()
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | import setuptools, glob
2 | from pathlib import Path
3 |
4 | #note: build this package with the following command:
5 | #pip wheel --no-deps -w dist .
6 |
7 | base_path = Path(__file__).parent
8 | long_description = (base_path / "README.md").read_text()
9 |
10 | setuptools.setup(
11 | name="poe-api",
12 | version="0.5.3",
13 | author="ading2210",
14 | license="GPLv3",
15 | description="A reverse engineered API wrapper for Quora's Poe",
16 | long_description=long_description,
17 | long_description_content_type="text/markdown",
18 | packages=["poe"],
19 | classifiers=[
20 | "Programming Language :: Python :: 3",
21 | "License :: OSI Approved :: GNU General Public License (GPL)",
22 | "Operating System :: OS Independent"
23 | ],
24 | python_requires=">=3.7",
25 | package_dir={
26 | "": "src"
27 | },
28 | package_data={
29 | "poe": ["poe_graphql/*.json"]
30 | },
31 | include_package_data=True,
32 | install_requires=[
33 | "websocket-client",
34 | "httpx",
35 | "brotlicffi",
36 | "tls_client",
37 | "quickjs"
38 | ],
39 | url="https://github.com/ading2210/poe-api"
40 | )
--------------------------------------------------------------------------------
/src/poe/__init__.py:
--------------------------------------------------------------------------------
1 | import re, json, random, logging, time, queue, threading, traceback, hashlib, string, random, os
2 | import quickjs
3 | import httpx
4 | import secrets
5 | import websocket
6 | import uuid
7 | import random
8 | from pathlib import Path
9 | from urllib.parse import urlparse
10 |
11 | parent_path = Path(__file__).resolve().parent
12 | queries_path = parent_path / "poe_graphql" / "queries.json"
13 | queries = {}
14 |
15 | logging.basicConfig()
16 | logger = logging.getLogger()
17 | logger.error("This library is unmaintained and will not work. See https://github.com/ading2210/poe-api/issues/231 for more details.")
18 |
19 | user_agent = "This will be ignored! See the README for info on how to set custom headers."
20 | headers = {
21 | "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36",
22 | "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
23 | "Accept-Encoding": "gzip, deflate, br",
24 | "Accept-Language": "en-US,en;q=0.9",
25 | "Sec-Ch-Ua": "\"Not.A/Brand\";v=\"8\", \"Chromium\";v=\"112\"",
26 | "Sec-Ch-Ua-Mobile": "?0",
27 | "Sec-Ch-Ua-Platform": "\"Linux\"",
28 | "Upgrade-Insecure-Requests": "1"
29 | }
30 | client_identifier = "chrome112"
31 |
32 | #load gql queries
33 | try:
34 | queries = json.loads(queries_path.read_text())
35 | except FileNotFoundError:
36 | logger.error("GraphQL queries file not found.")
37 | queries = {}
38 |
39 | def generate_payload(query_name, variables):
40 | if query_name == "recv":
41 | return generate_recv_payload(variables)
42 | return {
43 | "extensions": {
44 | "hash": queries[query_name]
45 | },
46 | "queryName": query_name,
47 | "variables": variables
48 | }
49 |
50 | def generate_recv_payload(variables):
51 | payload = [
52 | {
53 | "category": "poe/bot_response_speed",
54 | "data": variables,
55 | }
56 | ]
57 |
58 | if random.random() > 0.9:
59 | payload.append({
60 | "category": "poe/statsd_event",
61 | "data": {
62 | "key": "poe.speed.web_vitals.INP",
63 | "value": random.randint(100, 125),
64 | "category": "time",
65 | "path": "/[handle]",
66 | "extra_data": {},
67 | },
68 | })
69 |
70 | return payload
71 |
72 | def request_with_retries(method, *args, **kwargs):
73 | attempts = kwargs.get("attempts") or 10
74 | url = args[0]
75 | for i in range(attempts):
76 | r = method(*args, **kwargs)
77 | if r.status_code == 200:
78 | return r
79 | if r.status_code == 307:
80 | if r.headers.get("Location").startswith("/login"):
81 | raise RuntimeError("Invalid or missing token.")
82 | logger.warn(f"Server returned a status code of {r.status_code} while downloading {url}. Retrying ({i+1}/{attempts})...")
83 |
84 | raise RuntimeError(f"Failed to download {url} too many times.")
85 |
86 | def generate_nonce(length:int=16):
87 | return "".join(secrets.choice(string.ascii_letters + string.digits) for i in range(length))
88 |
89 | def get_config_path():
90 | if os.name == "nt":
91 | return Path.home() / "AppData" / "Roaming" / "poe-api"
92 | return Path.home() / ".config" / "poe-api"
93 |
94 | def set_saved_device_id(user_id, device_id):
95 | device_id_path = get_config_path() / "device_id.json"
96 | device_ids = {}
97 | if device_id_path.exists():
98 | with open(device_id_path) as f:
99 | device_ids = json.loads(f.read())
100 |
101 | device_ids[user_id] = device_id
102 | device_id_path.parent.mkdir(parents=True, exist_ok=True)
103 | with open(device_id_path, "w") as f:
104 | f.write(json.dumps(device_ids, indent=2))
105 |
106 | def get_saved_device_id(user_id):
107 | device_id_path = get_config_path() / "device_id.json"
108 | device_ids = {}
109 | if device_id_path.exists():
110 | with open(device_id_path) as f:
111 | device_ids = json.loads(f.read())
112 |
113 | if user_id in device_ids:
114 | return device_ids[user_id]
115 |
116 | device_id = str(uuid.uuid4())
117 | device_ids[user_id] = device_id
118 | device_id_path.parent.mkdir(parents=True, exist_ok=True)
119 | with open(device_id_path, "w") as f:
120 | f.write(json.dumps(device_ids, indent=2))
121 |
122 | return device_id
123 |
124 | class Client:
125 | gql_url = "https://poe.com/api/gql_POST"
126 | gql_recv_url = "https://poe.com/api/receive_POST"
127 | home_url = "https://poe.com"
128 | settings_url = "https://poe.com/api/settings"
129 |
130 | def __init__(self, token, proxy=None, headers=headers, device_id=None, client_identifier=client_identifier, formkey=None):
131 | self.ws_connecting = False
132 | self.ws_connected = False
133 | self.ws_error = False
134 | self.connect_count = 0
135 | self.setup_count = 0
136 |
137 | self.token = token
138 | self.device_id = device_id
139 | self.proxy = proxy
140 | self.client_identifier = client_identifier
141 |
142 | self.active_messages = {}
143 | self.message_queues = {}
144 | self.suggestion_callbacks = {}
145 |
146 | self.headers = {**headers, **{
147 | "Cache-Control": "no-cache",
148 | "Sec-Fetch-Dest": "document",
149 | "Sec-Fetch-Mode": "navigate",
150 | "Sec-Fetch-Site": "same-origin",
151 | "Sec-Fetch-User": "?1",
152 | }}
153 | self.formkey_salt = None
154 | self.formkey = formkey
155 |
156 | self.connect_ws()
157 |
158 | def setup_session(self):
159 | logger.info("Setting up session...")
160 | self.session = httpx.Client()
161 |
162 | """
163 | if self.client_identifier:
164 | self.session = requests_tls.Session(client_identifier=self.client_identifier)
165 | else:
166 | self.session = requests.Session()
167 | """
168 |
169 |
170 | if self.proxy:
171 | self.session.proxies = {
172 | "http": self.proxy,
173 | "https": self.proxy
174 | }
175 | logger.info(f"Proxy enabled: {self.proxy}")
176 |
177 | self.session.cookies.set("p-b", self.token, domain="poe.com")
178 | self.session.headers.update(self.headers)
179 |
180 | def setup_connection(self):
181 | if self.setup_count % 5 == 0:
182 | self.setup_session()
183 |
184 | self.setup_count += 1
185 |
186 | self.ws_domain = f"tch{random.randint(1, 1e6)}"
187 | self.next_data = self.get_next_data(overwrite_vars=True)
188 | self.channel = self.get_channel_data()
189 |
190 | self.gql_headers = {
191 | "poe-formkey": self.formkey,
192 | "poe-tchannel": self.channel["channel"],
193 | "Sec-Fetch-Dest": "empty",
194 | "Sec-Fetch-Mode": "cors",
195 | "Sec-Fetch-Site": "same-origin",
196 | }
197 | self.gql_headers = {**self.gql_headers, **self.headers}
198 |
199 | if not hasattr(self, "bots"):
200 | self.bots = self.get_bots(download_next_data=False)
201 | if not hasattr(self, "bot_names"):
202 | self.bot_names = self.get_bot_names()
203 |
204 | if self.device_id is None:
205 | self.device_id = self.get_device_id()
206 |
207 | self.subscribe()
208 |
209 | def get_device_id(self):
210 | user_id = self.viewer["poeUser"]["id"]
211 | device_id = get_saved_device_id(user_id)
212 | return device_id
213 |
214 | def extract_formkey(self, html, app_script):
215 | script_regex = r''
216 | vars_regex = r'window\._([a-zA-Z0-9]{10})="([a-zA-Z0-9]{10})"'
217 | key, value = re.findall(vars_regex, app_script)[0]
218 |
219 | script_text = """
220 | let QuickJS = undefined, process = undefined;
221 | let document = {a: 1};
222 | let window = {
223 | navigator: {
224 | userAgent: "a"
225 | }
226 | };
227 | """
228 | script_text += f"window._{key} = '{value}';"
229 | script_text += "".join(re.findall(script_regex, html)[:2])
230 |
231 | function_regex = r'(window\.[a-zA-Z0-9]{17})=function'
232 | function_text = re.search(function_regex, script_text).group(1)
233 | script_text += f"{function_text}();"
234 |
235 | context = quickjs.Context()
236 | formkey = context.eval(script_text)
237 |
238 | salt = None
239 | try:
240 | salt_function_regex = r'function (.)\(_0x[0-9a-f]{6},_0x[0-9a-f]{6},_0x[0-9a-f]{6}\)'
241 | salt_function = re.search(salt_function_regex, script_text).group(1)
242 | salt_script = f"{salt_function}(a=>a, '', '');"
243 | salt = context.eval(salt_script)
244 | except Exception as e:
245 | logger.warn("Failed to obtain poe-tag-id salt: "+str(e))
246 | logger.warn("Falling back to hardcoded value. Detection may be more likely.")
247 |
248 | return formkey, salt
249 |
250 | def get_next_data(self, overwrite_vars=False):
251 | logger.info("Downloading next_data...")
252 |
253 | r = request_with_retries(self.session.get, self.home_url)
254 | json_regex = r''
255 | json_text = re.search(json_regex, r.text).group(1)
256 | next_data = json.loads(json_text)
257 |
258 | if overwrite_vars:
259 | if not self.formkey:
260 | script_src_regex = r'src="(https://psc2\.cf2\.poecdn\.net/[a-f0-9]{40}/_next/static/chunks/pages/_app-[a-f0-9]{16}\.js)"'
261 | script_src = re.search(script_src_regex, r.text).group(1)
262 | r2 = request_with_retries(self.session.get, script_src)
263 | self.formkey, self.formkey_salt = self.extract_formkey(r.text, r2.text)
264 |
265 | if self.formkey_salt is None:
266 | self.formkey_salt = "3L346H46q37gXddko"
267 |
268 | self.viewer = next_data["props"]["initialData"]["data"]["pageQuery"]["viewer"]
269 | self.user_id = self.viewer["poeUser"]["id"]
270 | self.next_data = next_data
271 |
272 | return next_data
273 |
274 | def get_bot(self, handle):
275 | url = f'https://poe.com/_next/data/{self.next_data["buildId"]}/{handle}.json'
276 |
277 | data = request_with_retries(self.session.get, url).json()
278 | chat_data = data["pageProps"]["data"]["chatOfBotHandle"]
279 | return chat_data
280 |
281 | def get_bots(self, download_next_data=True):
282 | logger.info("Downloading all bots...")
283 | if not "availableBotsConnection" in self.viewer:
284 | raise RuntimeError("Invalid token or no bots are available.")
285 |
286 | bot_list_data = self.send_query("BotSwitcherModalQuery", {})["data"]["viewer"]["availableBotsConnection"]
287 | bot_list = bot_list_data["edges"]
288 | next_page = bot_list_data["pageInfo"]["hasNextPage"]
289 | end_cursor = bot_list_data["pageInfo"]["endCursor"]
290 |
291 | while next_page:
292 | bot_list_data = self.send_query("AvailableBotsListModalPaginationQuery", {
293 | "cursor": end_cursor,
294 | "limit": 10
295 | })["data"]["viewer"]["availableBotsConnection"]
296 | bot_list += bot_list_data["edges"]
297 | next_page = bot_list_data["pageInfo"]["hasNextPage"]
298 | end_cursor = bot_list_data["pageInfo"]["endCursor"]
299 |
300 | threads = []
301 | bots = {}
302 |
303 | def get_bot_thread(bot):
304 | chat_data = self.get_bot(bot["node"]["handle"])
305 | bots[chat_data["defaultBotObject"]["nickname"]] = chat_data
306 |
307 | for bot in bot_list:
308 | thread = threading.Thread(target=get_bot_thread, args=(bot,), daemon=True)
309 | threads.append(thread)
310 |
311 | for thread in threads:
312 | thread.start()
313 | for thread in threads:
314 | thread.join()
315 |
316 | self.bots = bots
317 | self.bot_names = self.get_bot_names()
318 | return bots
319 |
320 | def get_bot_by_codename(self, bot_codename):
321 | if bot_codename in self.bots:
322 | return self.bots[bot_codename]
323 |
324 | #todo: cache this so it isn't re-downloaded every time
325 | return self.get_bot(bot_codename)
326 |
327 | def get_bot_names(self):
328 | bot_names = {}
329 | for bot_nickname in self.bots:
330 | bot_obj = self.bots[bot_nickname]["defaultBotObject"]
331 | bot_names[bot_nickname] = bot_obj["displayName"]
332 | return bot_names
333 |
334 | def explore_bots(self, end_cursor=None, count=25):
335 | if not end_cursor:
336 | url = f'https://poe.com/_next/data/{self.next_data["buildId"]}/explore_bots.json'
337 | r = request_with_retries(self.session.get, url).json()
338 | data = r["pageProps"].get("payload") or r["pageProps"]["data"]
339 | nodes = data["exploreBotsConnection"]["edges"]
340 | bots = [node["node"] for node in nodes]
341 | bots = bots[:count]
342 | return {
343 | "bots": bots,
344 | "end_cursor": data["exploreBotsConnection"]["pageInfo" ]["endCursor"],
345 | }
346 |
347 | else:
348 | # Use graphql to get the next page
349 | result = self.send_query("ExploreBotsListPaginationQuery", {
350 | "count": count,
351 | "cursor": end_cursor
352 | })
353 | result = result["data"]["exploreBotsConnection"]
354 |
355 | bots = [node["node"] for node in result["edges"]]
356 | return {
357 | "bots": bots,
358 | "end_cursor": result["pageInfo"]["endCursor"],
359 | }
360 |
361 | def get_remaining_messages(self, chatbot):
362 | chat_data = self.get_bot_by_codename(chatbot)
363 | return chat_data["defaultBotObject"]["messageLimit"]["numMessagesRemaining"]
364 |
365 | def get_channel_data(self, channel=None):
366 | logger.info("Downloading channel data...")
367 | r = request_with_retries(self.session.get, self.settings_url)
368 | data = r.json()
369 |
370 | return data["tchannelData"]
371 |
372 | def get_websocket_url(self, channel=None):
373 | if channel is None:
374 | channel = self.channel
375 | query = f'?min_seq={channel["minSeq"]}&channel={channel["channel"]}&hash={channel["channelHash"]}'
376 | return f'ws://{self.ws_domain}.tch.{channel["baseHost"]}/up/{channel["boxName"]}/updates'+query
377 |
378 | def send_query(self, query_name, variables, attempts=20):
379 | for i in range(attempts):
380 | json_data = generate_payload(query_name, variables)
381 | payload = json.dumps(json_data, separators=(",", ":"))
382 |
383 | base_string = payload + self.gql_headers["poe-formkey"] + self.formkey_salt
384 |
385 | headers = {
386 | "content-type": "application/json",
387 | "poe-tag-id": hashlib.md5(base_string.encode()).hexdigest()
388 | }
389 | headers = {**self.gql_headers, **headers}
390 |
391 | if query_name == "recv":
392 | r = request_with_retries(self.session.post, self.gql_recv_url, data=payload, headers=headers)
393 | return None
394 |
395 | r = request_with_retries(self.session.post, self.gql_url, data=payload, headers=headers)
396 | data = r.json()
397 | if data["data"] == None:
398 | logger.warn(f'{query_name} returned an error: {data["errors"][0]["message"]} | Retrying ({i+1}/20) | Response: {data}')
399 | time.sleep(2)
400 | continue
401 |
402 | return r.json()
403 |
404 | raise RuntimeError(f'{query_name} failed too many times.')
405 |
406 | def subscribe(self):
407 | logger.info("Subscribing to mutations")
408 | result = self.send_query("SubscriptionsMutation", {
409 | "subscriptions": [
410 | {
411 | "subscriptionName": "messageAdded",
412 | "queryHash": queries["MessageAdded"],
413 | "query": None
414 | },
415 | {
416 | "subscriptionName": "viewerStateUpdated",
417 | "queryHash": queries["ViewerStateUpdated"],
418 | "query": None
419 | }
420 | ]
421 | })
422 |
423 | def ws_run_thread(self):
424 | kwargs = {}
425 | if self.proxy:
426 | proxy_parsed = urlparse(self.proxy)
427 | kwargs = {
428 | "proxy_type": proxy_parsed.scheme,
429 | "http_proxy_host": proxy_parsed.hostname,
430 | "http_proxy_port": proxy_parsed.port
431 | }
432 |
433 | # auth if exists
434 | if proxy_parsed.username and proxy_parsed.password:
435 | kwargs["http_proxy_auth"] = (proxy_parsed.username, proxy_parsed.password)
436 |
437 | self.ws.run_forever(**kwargs)
438 |
439 | def connect_ws(self, timeout=5):
440 | if self.ws_connected:
441 | return
442 |
443 | if self.ws_connecting:
444 | while not self.ws_connected:
445 | time.sleep(0.01)
446 | return
447 |
448 | self.ws_connecting = True
449 | self.ws_connected = False
450 |
451 | if self.connect_count % 5 == 0:
452 | self.setup_connection()
453 |
454 | self.connect_count += 1
455 |
456 | ws = websocket.WebSocketApp(
457 | self.get_websocket_url(),
458 | header={"User-Agent": user_agent},
459 | on_message=self.on_message,
460 | on_open=self.on_ws_connect,
461 | on_error=self.on_ws_error,
462 | on_close=self.on_ws_close
463 | )
464 |
465 | self.ws = ws
466 |
467 | t = threading.Thread(target=self.ws_run_thread, daemon=True)
468 | t.start()
469 |
470 | timer = 0
471 | while not self.ws_connected:
472 | time.sleep(0.01)
473 | timer += 0.01
474 | if timer > timeout:
475 | self.ws_connecting = False
476 | self.ws_connected = False
477 | self.ws_error = True
478 | ws.close()
479 | raise RuntimeError("Timed out waiting for websocket to connect.")
480 |
481 | def disconnect_ws(self):
482 | self.ws_connecting = False
483 | self.ws_connected = False
484 | if self.ws:
485 | self.ws.close()
486 |
487 | def on_ws_connect(self, ws):
488 | self.ws_connecting = False
489 | self.ws_connected = True
490 |
491 | def on_ws_close(self, ws, close_status_code, close_message):
492 | logger.warn(f"Websocket closed with status {close_status_code}: {close_message}")
493 |
494 | self.ws_connecting = False
495 | self.ws_connected = False
496 | if self.ws_error:
497 | self.ws_error = False
498 | self.connect_ws()
499 |
500 | def on_ws_error(self, ws, error):
501 | self.ws_connecting = False
502 | self.ws_connected = False
503 | self.ws_error = True
504 |
505 | def on_message(self, ws, msg):
506 | try:
507 | data = json.loads(msg)
508 |
509 | if not "messages" in data:
510 | return
511 |
512 | for message_str in data["messages"]:
513 | message_data = json.loads(message_str)
514 | if message_data["message_type"] != "subscriptionUpdate":
515 | continue
516 | message = message_data["payload"]["data"]["messageAdded"]
517 |
518 | #handle suggested replies
519 | if "suggestedReplies" in message and type(message["suggestedReplies"]) == list and len(message["suggestedReplies"]) > 0 and message["messageId"] in self.suggestion_callbacks:
520 | self.suggestion_callbacks[message["messageId"]](message["suggestedReplies"][-1])
521 | if len(message["suggestedReplies"]) >= 3:
522 | del self.suggestion_callbacks[message["messageId"]]
523 |
524 | copied_dict = self.active_messages.copy()
525 | for key, value in copied_dict.items():
526 | #add the message to the appropriate queue
527 | if value == message["messageId"] and key in self.message_queues:
528 | self.message_queues[key].put(message)
529 | return
530 |
531 | #indicate that the response id is tied to the human message id
532 | elif key != "pending" and value == None and message["state"] != "complete":
533 | self.active_messages[key] = message["messageId"]
534 | self.message_queues[key].put(message)
535 | return
536 |
537 | except Exception:
538 | logger.error(traceback.format_exc())
539 | self.disconnect_ws()
540 | self.connect_ws()
541 |
542 | def is_busy(self):
543 | return bool(self.active_messages)
544 |
545 | def send_message(self, chatbot, message, with_chat_break=False, timeout=20, async_recv=True, suggest_callback=None):
546 | # if there is another active message, wait until it has finished sending
547 | timer = 0
548 | while None in self.active_messages.values():
549 | time.sleep(0.01)
550 | timer += 0.01
551 | if timer > timeout:
552 | raise RuntimeError("Timed out waiting for other messages to send.")
553 |
554 | # None indicates that a message is still in progress
555 | self.active_messages["pending"] = None
556 |
557 | # reconnect websocket
558 | while self.ws_error:
559 | time.sleep(0.01)
560 |
561 | self.connect_ws()
562 |
563 | logger.info(f"Sending message to {chatbot}: {message}")
564 |
565 | chat_id = self.get_bot_by_codename(chatbot)["chatId"]
566 | try:
567 | message_data = self.send_query("SendMessageMutation", {
568 | "bot": chatbot,
569 | "query": message,
570 | "chatId": chat_id,
571 | "source": {
572 | "chatInputMetadata": {
573 | "useVoiceRecord": False
574 | },
575 | "sourceType": "chat_input"
576 | },
577 | "clientNonce": generate_nonce(),
578 | "sdid": self.device_id,
579 | "withChatBreak": with_chat_break,
580 | "attachments": []
581 | })
582 | del self.active_messages["pending"]
583 | except Exception as e:
584 | del self.active_messages["pending"]
585 | raise e
586 |
587 | if not message_data["data"]["messageEdgeCreate"]["message"]:
588 | raise RuntimeError(f"Daily limit reached for {chatbot}.")
589 | try:
590 | human_message = message_data["data"]["messageEdgeCreate"]["message"]
591 | human_message_id = human_message["node"]["messageId"]
592 | except TypeError:
593 | raise RuntimeError(f"An unknown error occurred. Raw response data: {message_data}")
594 |
595 | # indicate that the current message is waiting for a response
596 | self.active_messages[human_message_id] = None
597 | self.message_queues[human_message_id] = queue.Queue()
598 |
599 | last_text = ""
600 | message_id = None
601 | while True:
602 | try:
603 | message = self.message_queues[human_message_id].get(timeout=timeout)
604 | except queue.Empty:
605 | del self.active_messages[human_message_id]
606 | del self.message_queues[human_message_id]
607 | raise RuntimeError("Response timed out.")
608 |
609 | #only break when the message is marked as complete
610 | if message["state"] == "complete":
611 | if last_text and message["messageId"] == message_id:
612 | break
613 | else:
614 | continue
615 |
616 | #update info about response
617 | message["text_new"] = message["text"][len(last_text):]
618 | last_text = message["text"]
619 | message_id = message["messageId"]
620 |
621 | # set a suggestion callback on response
622 | if callable(suggest_callback) and not message_id in self.suggestion_callbacks:
623 | self.suggestion_callbacks[message_id] = suggest_callback
624 |
625 | yield message
626 |
627 | def recv_post_thread():
628 | bot_message_id = self.active_messages[human_message_id]
629 |
630 | # wait 2 seconds after sending the request
631 | time.sleep(2.5)
632 |
633 | # send recv_post after receiving the last message
634 | self.send_query("recv", {
635 | "bot": chatbot,
636 | "time_to_first_typing_indicator": 300, # randomly select
637 | "time_to_first_subscription_response": 600,
638 | "time_to_full_bot_response": 1100,
639 | "full_response_length": len(last_text) + 1,
640 | "full_response_word_count": len(last_text.split(" ")) + 1,
641 | "human_message_id": human_message_id,
642 | "bot_message_id": bot_message_id,
643 | "chat_id": chat_id,
644 | "bot_response_status": "success",
645 | })
646 | time.sleep(0.5)
647 |
648 | t = threading.Thread(target=recv_post_thread, daemon=True)
649 | t.start()
650 | if not async_recv:
651 | t.join()
652 |
653 | del self.active_messages[human_message_id]
654 | del self.message_queues[human_message_id]
655 |
656 | def send_chat_break(self, chatbot):
657 | logger.info(f"Sending chat break to {chatbot}")
658 | result = self.send_query("AddMessageBreakEdgeMutation", {
659 | "chatId": self.get_bot_by_codename(chatbot)["chatId"],
660 | "connections": []
661 | })
662 | return result["data"]["messageBreakEdgeCreate"]["message"]
663 |
664 | def get_message_history(self, chatbot, count=25, cursor=None):
665 | logger.info(f"Downloading {count} messages from {chatbot}")
666 |
667 | messages = []
668 | if cursor == None:
669 | if not chatbot in self.bots:
670 | chat_data = self.get_bot(chatbot)
671 | else:
672 | chat_data = self.get_bot(self.bot_names[chatbot])
673 |
674 | if not chat_data["messagesConnection"]["edges"]:
675 | return []
676 | messages = chat_data["messagesConnection"]["edges"][-count:]
677 | cursor = chat_data["messagesConnection"]["pageInfo"]["startCursor"]
678 | count -= len(messages)
679 |
680 | cursor = str(cursor)
681 | if count > 50:
682 | messages = self.get_message_history(chatbot, count=50, cursor=cursor) + messages
683 | while count > 0:
684 | count -= 50
685 | new_cursor = messages[0]["cursor"]
686 | new_messages = self.get_message_history(chatbot, min(50, count), cursor=new_cursor)
687 | messages = new_messages + messages
688 | return messages
689 | elif count <= 0:
690 | return messages
691 |
692 | result = self.send_query("ChatListPaginationQuery", {
693 | "count": count,
694 | "cursor": cursor,
695 | "id": self.get_bot_by_codename(chatbot)["id"]
696 | })
697 | query_messages = result["data"]["node"]["messagesConnection"]["edges"]
698 | messages = query_messages + messages
699 | return messages
700 |
701 | def delete_message(self, message_ids):
702 | logger.info(f"Deleting messages: {message_ids}")
703 | if not type(message_ids) is list:
704 | message_ids = [int(message_ids)]
705 |
706 | result = self.send_query("DeleteUserMessagesMutation", {
707 | "messageIds": message_ids
708 | })
709 |
710 | def purge_conversation(self, chatbot, count=-1):
711 | logger.info(f"Purging messages from {chatbot}")
712 | last_messages = self.get_message_history(chatbot, count=50)[::-1]
713 | while last_messages:
714 | message_ids = []
715 | for message in last_messages:
716 | if count == 0:
717 | break
718 | count -= 1
719 | message_ids.append(message["node"]["messageId"])
720 |
721 | self.delete_message(message_ids)
722 |
723 | if count == 0:
724 | return
725 | last_messages = self.get_message_history(chatbot, count=50)[::-1]
726 |
727 | logger.info(f"No more messages left to delete.")
728 |
729 | def create_bot(self, handle, prompt, display_name=None, base_model="chinchilla", description="",
730 | intro_message="", api_key=None, api_bot=False, api_url=None,
731 | prompt_public=True, pfp_url=None, linkification=False,
732 | markdown_rendering=True, suggested_replies=False, private=False,
733 | temperature=None):
734 | result = self.send_query("PoeBotCreate", {
735 | "model": base_model,
736 | "displayName": display_name,
737 | "handle": handle,
738 | "prompt": prompt,
739 | "isPromptPublic": prompt_public,
740 | "introduction": intro_message,
741 | "description": description,
742 | "profilePictureUrl": pfp_url,
743 | "apiUrl": api_url,
744 | "apiKey": api_key,
745 | "isApiBot": api_bot,
746 | "hasLinkification": linkification,
747 | "hasMarkdownRendering": markdown_rendering,
748 | "hasSuggestedReplies": suggested_replies,
749 | "isPrivateBot": private,
750 | "temperature": temperature
751 | })
752 |
753 | data = result["data"]["poeBotCreate"]
754 | if data["status"] != "success":
755 | raise RuntimeError(f"Poe returned an error while trying to create a bot: {data['status']}")
756 | self.get_bots()
757 | return data
758 |
759 | def edit_bot(self, bot_id, handle, prompt, display_name=None, base_model="chinchilla", description="",
760 | intro_message="", api_key=None, api_url=None, private=False,
761 | prompt_public=True, pfp_url=None, linkification=False,
762 | markdown_rendering=True, suggested_replies=False, temperature=None, new_handle=None):
763 |
764 | if bot_id is None and handle is not None:
765 | bot_id = self.get_bot(handle)["defaultBotObject"]["botId"]
766 | new_handle = new_handle or handle
767 |
768 | result = self.send_query("PoeBotEdit", {
769 | "baseBot": base_model,
770 | "botId": bot_id,
771 | "handle": new_handle,
772 | "displayName": display_name,
773 | "prompt": prompt,
774 | "isPromptPublic": prompt_public,
775 | "introduction": intro_message,
776 | "description": description,
777 | "profilePictureUrl": pfp_url,
778 | "apiUrl": api_url,
779 | "apiKey": api_key,
780 | "hasLinkification": linkification,
781 | "hasMarkdownRendering": markdown_rendering,
782 | "hasSuggestedReplies": suggested_replies,
783 | "isPrivateBot": private,
784 | "temperature": temperature
785 | })
786 |
787 | data = result["data"]["poeBotEdit"]
788 | if data["status"] != "success":
789 | raise RuntimeError(f"Poe returned an error while trying to edit a bot: {data['status']}")
790 | self.get_bots()
791 | return data
792 |
793 | def purge_all_conversations(self):
794 | logger.info("Purging all conversations")
795 | self.send_query("DeleteUserMessagesMutation", {})
796 |
--------------------------------------------------------------------------------
/src/poe/hashes.py:
--------------------------------------------------------------------------------
1 | import httpx
2 | import poe
3 | import re
4 | import json
5 | import pathlib
6 |
7 | #running this file will export the gql query ids to poe_graphql/queries.json
8 |
9 | if __name__ == "__main__":
10 | session = httpx.Client()
11 | headers = {**poe.headers, **{
12 | "Cache-Control": "no-cache",
13 | "Sec-Fetch-Dest": "document",
14 | "Sec-Fetch-Mode": "navigate",
15 | "Sec-Fetch-Site": "same-origin",
16 | "Sec-Fetch-User": "?1",
17 | }}
18 | session.headers.update(headers)
19 |
20 | r = session.get("https://poe.com/login?redirect_url=%2F")
21 | manifest_regex = r'https://psc2\.cf2\.poecdn\.net/[0-9a-f]{40}/_next/static/\S{21}/_buildManifest\.js'
22 | base_regex = r'https://psc2\.cf2\.poecdn\.net/[0-9a-f]{40}/_next/'
23 | chunks_regex = r'\"(https://psc2\.cf2\.poecdn\.net/[0-9a-f]{40}/_next/static/chunks.+?.js)"'
24 | webpack_regex = r'\"(https://psc2\.cf2\.poecdn\.net/[0-9a-f]{40}/_next/static/chunks/webpack.+?.js)"'
25 |
26 | chunks = re.findall(chunks_regex, r.text)
27 | manifest_url = re.findall(manifest_regex, r.text)[0]
28 | webpack_url = re.findall(webpack_regex, r.text)[0]
29 | base_url = re.findall(base_regex, r.text)[0]
30 |
31 | r2 = session.get(manifest_url)
32 | resources_regex = r'"(static/.+?)"'
33 | resources_list = re.findall(resources_regex, r2.text)
34 | urls = []
35 |
36 | r3 = session.get(webpack_url)
37 | webpack_chunks_regex = r'\+\(({.+?})\)\[.\]\+"\.js"'
38 | webpack_items_regex = r'(\d+):"([0-9a-f]{16})"'
39 | json_text = re.findall(webpack_chunks_regex, r3.text)[0]
40 | webpack_chunks = re.findall(webpack_items_regex, json_text)
41 |
42 | for chunk_id, chunk_hash in webpack_chunks:
43 | urls.append(base_url + f"static/chunks/{chunk_id}.{chunk_hash}.js")
44 | for resource in resources_list:
45 | urls.append(base_url + resource)
46 | urls = list(set(urls + chunks))
47 |
48 | queries = {}
49 | for url in urls:
50 | print("Downloading and parsing "+url)
51 | if not url.endswith(".js"):
52 | continue
53 |
54 | r4 = session.get(url)
55 | if r4.status_code != 200:
56 | continue
57 |
58 | hashes_regex = r'params:{id:"([0-9a-f]{64})".+?name:"(\S+?)"'
59 | hashes_list = re.findall(hashes_regex, r4.text)
60 |
61 | for query_hash, query_name in hashes_list:
62 | if "_" in query_name:
63 | query_name = query_name.split("_")[1]
64 | query_name = query_name[0].upper()+query_name[1:]
65 | queries[query_name] = query_hash
66 |
67 | json_text = json.dumps(queries, indent=2, sort_keys=True)
68 | poe.queries_path.write_text(json_text)
--------------------------------------------------------------------------------
/src/poe/poe_graphql/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ading2210/poe-api/9286c02017f3102dc665afb631a3ebd00bd566ee/src/poe/poe_graphql/__init__.py
--------------------------------------------------------------------------------
/src/poe/poe_graphql/queries.json:
--------------------------------------------------------------------------------
1 | {
2 | "AddEmailMutation": "6d9ff3c8ed7badced30cfdad97492d4c21719931e8c44c5601abfa429b62ded7",
3 | "AddMessageBreakEdgeMutation": "9450e06185f46531eca3e650c26fa8524f876924d1a8e9a3fb322305044bdac3",
4 | "AddPhoneNumber": "26ae865f0686a910a86759c069eb1c0085d78b55a8abf64444ec63b03c76fb58",
5 | "AnnotateWithIdsProviderQuery": "b4e6992c3af8f208ab2b3979dce48889835736ed29f623ea9f609265018d0d8f",
6 | "AvailableBotsListModalPaginationQuery": "3be373baa573ccd196b9d71c94953b1d1bc586625bd64efe51655d75e68bbfb7",
7 | "AvailableBotsSelectorModalPaginationQuery": "dd9281852c9a4d9d598f5a215e0143a8f76972c08e84053793567f7a76572593",
8 | "BotInfoFormRunCheckMutation": "87d55551061151b852fd7c53ec34dbb1ae784516b0ba2df5255b201f0d4e1444",
9 | "BotInfoModalQuery": "d84c9e2fb3d698edb3c82b9eeca9ceee08ba6461a19bfcfd971f5c60c2dd9012",
10 | "BotLandingPageQuery": "fb2f3e506be25ff8ba658bf55cd2228dec374855b6758ec406f0d1274bf5588d",
11 | "BotSelectorModalQuery": "b1ed351177d82da55670039a971c647b87874d28c5e137b8eb9c9fdf7fb30f7b",
12 | "BotSwitcherModalQuery": "54023ee8b691543982b2819491532532c317b899918e049617928137c26d47f5",
13 | "ChatDeleteConfirmationModalQuery": "716c8cc3ac6c13d6b41ceb2404e3a28c63aea6d166bf071dca1f98e0377727c3",
14 | "ChatHelpersSendNewChatMessageMutation": "943e16d73c3582759fa112842ef050e85d6f0048048862717ba861c828ef3f82",
15 | "ChatHistoryFilteredListPaginationQuery": "ea1894d73aa8a16d059c56696305c85761b11822f4f60e6471d1e24cb14100cf",
16 | "ChatHistoryListPaginationQuery": "9d52c1995f77c6f9a8c93956dbf79f4ab1024f5bfb797118727b29fed81eee7f",
17 | "ChatHomeMainInputContainerOptimisticBotQuery": "1c9267ecff73cb27a8e7d94a3f5b5fe665a82abe0fdd61be2e54dd38c0e61639",
18 | "ChatHomeMainInputContainerOptimisticViewerQuery": "21f0eb43ab07d97d4a30bcf007db4797b95e852fb6537e8dbbc002da45ba4fac",
19 | "ChatListPaginationQuery": "dc3f4d34f13ed0a22b0dbfa6a1924a18922f7fe3a392b059b0c8c2134ce4ec8a",
20 | "ChatLoaderQuery": "d9467ac216e21b510eb8e72a2888289d173c9d5ce399b072fd88bee3da1b1459",
21 | "ChatPageBotBotsPagination": "ed9017f85fe2fedbf02b2d000cb4b551d2ec870715d0c7bce6d54a0f3f9b657b",
22 | "ChatPageQuery": "63eee0aafc4d83a50fe7ceaec1853b191ea86b3d561268fa7aad24c69bb891d9",
23 | "ChatSetTitle": "24574aab7fedf86d1654bbc70bf5421abbc33e195aa1c11178697023a27a912e",
24 | "ChatSettingsModalQuery": "8685c8a92f57f318bd71b7e450b07a3d481bc12998e8015289fa3b4777d8a95e",
25 | "ChatSubscriptionPaywallModalQuery": "559ac4c7c8f0f6f50148d255bb6318107034375df7bca4214f608cd65b573a21",
26 | "ChatSwitcherRefetchQuery": "72b67c89c56430f17a539051a5983149e92d66d19cbbb8f841104cb8624f9ce7",
27 | "ChatTitleUpdated": "740e2c7ab27297b7a8acde39a400b932c71beb7e9b525280fc99c1639f1be93a",
28 | "ChatsHistoryPageQuery": "050767d78f19014e99493016ab2b708b619c7c044eebd838347cf259f0f2aefb",
29 | "ContinueChatFromPoeShare": "a220810c2d1d3b5284b6be44309a3d2b197c312a79b1a27f165a12f1508322bd",
30 | "ContinueChatIndexPageQuery": "a7eea6eebd14aa355723514558762315d0b4df46205b70f825d288d5ed1635ec",
31 | "ContinueChatPageQuery": "fe3a4d2006b1c4bb47ac6dea0639bc9128ad983cf37cbc0006c33efab372a19d",
32 | "CreateBotIndexPageQuery": "4baf597014ae930de3032c079b80dbb191c9be8be6a6ab12e79a79ddc803b770",
33 | "CreateChatMutation": "f1322c9c34d4140d420aeb9151cdeebc2235d381ada0037c845572310f613b7d",
34 | "CreateChatWithTitle": "6cf8cddd6594901bd4a7dc6ddeffc91485c21c817e8f7fa07fae9d71d9807d71",
35 | "CreateCheckoutSession": "5eb43e7c83974acc6680e1abe4c169296d0b346c42cc20d487762163402ea8e5",
36 | "CreateCustomerPortalSession": "4d43136f33aba6b6dea2ac8cd295e03bd841b7c99bf772940fa06a623a331786",
37 | "CreateMessagesToContinueChatMutation": "00b66f0117fab1ab6cdcf7e98819c1e3196736253b6a158316a49f587b964d25",
38 | "DeleteAccountMutation": "4e9651277464843d4d42fbfb5b4ccb1c348e3efe090d6971fa7a3c2cabc7ea5c",
39 | "DeleteChat": "5df4cb75c0c06e086b8949890b1871a9f8b9e431a930d5894d08ca86e9260a18",
40 | "DeleteMessageMutation": "8d1879c2e851ba163badb6065561183600fc1b9de99fc8b48b654eb65af92bed",
41 | "DeleteUserMessagesMutation": "3f60d527c3f636f308b3a26fc3a0012be34ea1a201e47a774b4513d8a1ba8912",
42 | "DismissDismissible": "b133084411c0a7a2353f6cfacd3d115260c34ddc5d97cf7f19a16e8cb4410803",
43 | "EditBotIndexPageQuery": "2da47ecf6bbae7e17769eba670e6e553aea61464c021a809c57af8b5a1e6596c",
44 | "EditBotPageQuery": "af5d874417150228c6ff9b32885185139a616991239f109b81946abe7a04bfb2",
45 | "EmailUnsubscribe": "eacf2ae89b7a30460619ccfb0d5a4e6007cfbcf0286ec7684c24192527a00263",
46 | "EmbedLoggedOutPageQuery": "e81580f4126215186e8a5d18bdedcf7c056b634d4d864f54b948765c8c21aef9",
47 | "ExploreBotsCarouselContainerQuery": "e46511b51cb2e9244225e1e6509c6a696dde271e45da74ce66853379eaeb80d6",
48 | "ExploreBotsCarouselLazyLoadedContainerQuery": "846522f24edbbad1331cedfe311ba0c8e365cf33aee1bb1e3f0e03156f1a0536",
49 | "ExploreBotsCarouselPagedContainerPaginationQuery": "619df00e336f6bbad2bbc2626aa74f97eb12efb50f403339cc780041aa9897e0",
50 | "ExploreBotsIndexPageQuery": "b6b0fb768c7727b57f4cb51489a3850ded36d1b96e27c1346f04171db0b2cf25",
51 | "ExploreBotsListPaginationQuery": "983be13fda71b7926b77f461ae7e8925c4e696cdd578fbfd42cb0d14103993ac",
52 | "ExploreBotsSidebarQuery": "00f42e3842c63cfcfcebad6402cdaa1df1c3fa7ffe3efbe0437a08a151eca87e",
53 | "GenerateAppleAuthNonceMutation": "c3e0c1b990cd17322716d0fa943a8ddc0ffecf45294ad013ccc883954c2171fc",
54 | "HandleBotChatEmbedPageQuery": "60a48e1b772e6830ddbdb54f19e837beef949d4fc146c51b1f50469f40b7650b",
55 | "HandleBotChatPageQuery": "dc1891a1d9b3ca42c773a69e9985f95e78a13ad5858cef0574c7f4ce87004a77",
56 | "HandleProfileIndexPageQuery": "0243e1784c33ae913d8a3ad20fc1252b930b6741ff9d78bd776e2df4f93f55ee",
57 | "HandleProfilePageQuery": "4605a49a28aa5647b96f437d61a8b9318e2619d9974c61759b0ec82b201befb7",
58 | "IntroMainQuery": "47f2c9bb41be5238968c81c82f2d2cff4100c73fcc70a9f592825bb40c0efc8d",
59 | "LayoutLeftSidebarQuery": "23d41c7aede6b0805cc9c02ac8d33c8f190467f15c8e1e003e882348d5f5ad6c",
60 | "LayoutRightSidebarQuery": "b5894b6a386e2d44431dba9e4d1cca0863b3783a031edf100cf998e1eb783225",
61 | "LoginPageQuery": "538d23244211dfe6ed3228518508ebc728f9f8165950d5a19fc5467c2f0b9a1f",
62 | "LoginWithVerificationCodeMutation": "0d5aecd57239d518c25dc972569ee77dd9610a114610a6a3e87b87fdd8f1ba90",
63 | "LogoutAllSessionsMutation": "1e62b26302959ca753def8678e817b2c1ad94efdb21872dbf0f8bffcb892aed4",
64 | "LogoutMutation": "1d2e52b19e15a6aa0ec93d8e4a3a9653b9ceb4c1f365c7d9c4451d835505eef2",
65 | "MarkAndroidAppDownloadPromptSeen": "ed6891c8913983cc4fd0bfed9760e9738743419712ce6681841217ed0bb8c915",
66 | "MarkMultiplayerNuxCompleted": "c1b1f2ce72d9f8e9cd7bbe1eecbf6e3bed3366df6a18b179b07ddfd9f1f8b3b1",
67 | "MessageAdded": "6d5ff500e4390c7a4ee7eeed01cfa317f326c781decb8523223dd2e7f33d3698",
68 | "MessageCancel": "59b10f19930cf95d3120612e72d271e3346a7fc9599e47183a593a05b68c617e",
69 | "MessageCancelled": "dfcedd9e0304629c22929725ff6544e1cb32c8f20b0c3fd54d966103ccbcf9d3",
70 | "MessageDeleted": "91f1ea046d2f3e21dabb3131898ec3c597cb879aa270ad780e8fdd687cde02a3",
71 | "MessageLimitUpdated": "d862b8febb4c058d8ad513a7c118952ad9095c4ec0a5471540133fc0a9bd3797",
72 | "MessageUnvoteMutation": "af2b91f09ab2ccf53ba9176a86b9934b98a865adf228b2ac3a548d6397f382f3",
73 | "MessageVoteMutation": "199fd8402c70ac10c5b05ba31587a0beff3acc39c7194362610ad50bf20299ed",
74 | "NewLandingPageQuery": "f36fbfcbad84b02876a254ba77ecf78f96360e77291766209b9e7655852440da",
75 | "NumTokensFromPromptQuery": "1d9bef79811f3b2ddca5ce4027b7eaa31a51bbeed1edf8b6f72e2e0d09d80609",
76 | "NuxInitialModalQuery": "f8cd0d8494afe3b5dbb349baa28d3ac21f2219ce699e2d59a2345c864905e0c3",
77 | "OnboardingFreeTrialModalQuery": "d2cc659e3def4561ca15b268a97588c5af6cd154afb001312aa69f63c5b2cc9e",
78 | "OnboardingPaywallModalQuery": "b413e41e89125528f1b2e7f472bde37f6f48a25cb774f4ea3ff883644c973cca",
79 | "OnboardingPaywallWithGraphicModalQuery": "f986cd3dc4fbab98927983c5d4ed78fa095af78392cf3880af9203dea975890d",
80 | "OptimisticChatLoaderQuery": "8633378bbe67e397457bebb256d7dc0c48f9a973315f3158cfb2f4fc08ad6c06",
81 | "PageBlockerQuery": "0ba776d55dc7ec768175737dc55362953590f94d0d34505f82571ac0feafcea7",
82 | "PageWrapperQuery": "bb7b40abdc44ee6865ddad6e90169c22a4ea35388c3192e448bcbcfd4b36cc1d",
83 | "PagesBotNameQuery": "a156136af92b189768540f864445f0b8d9191584530def6b1a5502c843539cfb",
84 | "PagesDefaultBotChatPageQuery": "75bd0877369c2b4191c936572822ce1875c980f1f6f8683381bd4a6850bdea92",
85 | "PoeBotCreate": "315cd7a2ce15ebb1f91b04c8fe3d22ad107325a0240ee439b07d5d949bd8c545",
86 | "PoeBotDelete": "c5e5ee2fdac007b02d074ce7882a0631bfbccc73d8833ba8765297c5ea782bb6",
87 | "PoeBotEdit": "717495e73bac650d03a03e4a2ad5a66ca10a8f068b1b781603ad4c56fd4951c2",
88 | "PoeBotFollow": "efa3f25f6cd67f9dea757be50305c0caa6a4e51f52ffba7e4a1c1f2c84d6dbd0",
89 | "PoeBotUnfollow": "db2281f3efa305db62d38964b640e982076491c2c59d5be3303feae343fe8914",
90 | "PoeRemoveBotFromUserList": "89e756b668b2318fa73c2a9dde4608a4529c74844667417c0cfb245e7e04e96e",
91 | "PoeSetBio": "66fb99ec59fa17bc4487f944d116bc920161faced58a3ce99e82cb61af61468e",
92 | "PoeSetHandle": "6024c7b6d40322fb376a84c43c8faf55f5f9f69f0af2e7bd82434296d6975f48",
93 | "PoeSetName": "c406a46fe6ff244ab2d665ea953fc8655d6816f1731505d830863d9b9c5021bf",
94 | "PoeSetProfilePhoto": "13106f2433e5d48a53e6804b76022e80c0fc9bf018eb5b5404d9e0a4acd94f1f",
95 | "PoeUserSetFollow": "dcc26e4e36b47af8af6bd0296ff85dfa8fc77a9c374ea5989afd0bf39ae4d35e",
96 | "PostIdPostPageQuery": "653c4768688ce6c8c14ca359ce536646b3de71a7e953c16381136399791c95a0",
97 | "ProfileIndexPageQuery": "4044ca7eb203e613f19dc76a4a05ca1df25bfdb2ff761a9d6dced6b0d61f219a",
98 | "ProfilePageQuery": "9505daf59f885463e5bd3bb2a1a9fc088e8634fbc7d5a0682f2ece11ee7548dd",
99 | "RemoveEmailMutation": "63750a7e41cc0ad3f6da0be1fdae9c243f1afab83cf44bb5c3df14243074681d",
100 | "RemoveUserPhoneNumberMutation": "7dadad6ac75a8a4e5c54479524c7821e748c043242476958262bb39fa60ccddb",
101 | "SaveContinueChatInfoMutation": "ae56678376401ae45dbba61aa6b1a55564877edc33605db6283e1dc3bdb0c8ff",
102 | "SearchResultsListPaginationQuery": "8466d0d19866f27eabef0657dc9a1822ed5260c44dc839d32cd9c329fe444e31",
103 | "SearchResultsMainQuery": "f8197cc6f654594d98c414e9cb6915d3004be06b15e1c20994c88bc882289211",
104 | "SelectorTestPageQuery": "9ec86fe8e3d0d3b264d0fab0feb73e38c86d616c7c3d8340d7a6146bd8445ed3",
105 | "SendMessageMutation": "5fd489242adf25bf399a95c6b16de9665e521b76618a97621167ae5e11e4bce4",
106 | "SendVerificationCodeMutation": "1b3d5a8c7fd8b187b14552d3d1ab13b19d5ea263e9716a207fedc23853c0b98a",
107 | "SetPrimaryEmailMutation": "01e75a6d937351b304ca9cc0b231e43587a5923e7f8618863bdf996df38d28b5",
108 | "SettingsDefaultBotSectionMutation": "4084604e8741af8650ac6b4236cdfa13c91a70cf1c63ad8a368706a386d0887e",
109 | "SettingsPageQuery": "1633485f58c7f2e730a34446b8566c40b5fe2a75ad82b930e3374d8c222b5983",
110 | "ShareCodeSharePageQuery": "e56f5cb9c7fc9872d053ddaef3dd7827067530b014f59e3ed07bc5e21a0f4334",
111 | "ShareMessageMutation": "2491190f42c1f5265d8dbaaaf7220dbfa094044fdfb2429fd7f2e35f863bc5e1",
112 | "SignupOrLoginWithAppleMutation": "074bf2533767ae06ced2046b538299b0ca7d8934da22ce6b7de51b666ffbfa30",
113 | "SignupOrLoginWithGoogleMutation": "571ab1eb99f58fd77dac19d5ee814e2fb10be4c1b430cc64c845af90985295f3",
114 | "SignupOrLoginWithQuoraMutation": "ee2498e8837e7b975806613401f5aa4ba18d03fdcc9fde0c59efc75717103df5",
115 | "SignupWallModalInnerQuery": "56f7718c8e586c16065f7b57dcbcf61d3789ab937590e8e77d458613b3c8f325",
116 | "SignupWithVerificationCodeMutation": "6a9b90b76ee9c058f55a3d659c093a5eca6a5ddbef233dbecee389501b1e5dbf",
117 | "StaticContentQuery": "15267bf130fbe298a6f60334f57ccf62bc16ff06c74d5778ba54b4b4f21f8d0c",
118 | "SubscriptionTosQuery": "6696950c5612023d877acd6a6f9026668960994825d3fa71a80528c316510c2f",
119 | "SubscriptionsMutation": "5a7bfc9ce3b4e456cd05a537cfa27096f08417593b8d9b53f57587f3b7b63e99",
120 | "UniversalLinkPageQuery": "1936c3260d5ece06722bbb402f55ce960efceaa1ad6f650a9358c9bf2960f546",
121 | "UpdatePhoneNumber": "c49f5f64947c2946f8007f366bbc0ca5b1f0bbbdc6b72ad97be90533f0e83c28",
122 | "UseBotSelectorBotQuery": "6af7249e90de59baef2e770f7e773f9f7730fd49db6b4e82035c49a078818534",
123 | "UseBotSelectorViewerBotsPaginationQuery": "e7dbf27efba69f014750ee56ac13f21262e76e161c6e58d435ae75935798d1b0",
124 | "UseStopMessageAndSendChatBreak": "9b95c61cd6cb41230a51fb360896454dde1ae6d1edb6f075504cb83a52422bc9",
125 | "UserEditBioModalQuery": "b78089f19d1071ad9440d5a2696588b0e82a012f6b40dca68f071cc0a49727f2",
126 | "UserEditHandleModalQuery": "ecee1f772c401f6e429ba7ebe088eedc0aa6d24dfa4cae0ec6f54bb3c5a5c653",
127 | "UserEditNameModalQuery": "dd72d69698a46097386b73b19677a84b6bcba51b3df3790e67d804b6da686787",
128 | "UserEditProfilePicModalQuery": "7f69ff6407a1360570863b09a9c02bf0a4bdbd8de2b04e5dde4eec031a6f62e5",
129 | "UserFolloweesListModalQuery": "b219f7e8b7c8d21aaa0979d44bfc3935501719e3fe18cbe86b459eced5f290d2",
130 | "UserFollowersListModalQuery": "86b007fa15b2de6f7eb527050832d342dde837aaedfb61bfdd1bf1201b860b61",
131 | "UserProfileConfigurePreviewModalQuery": "abec61f90eebcc3b914487db0ba35ff6ec53c1f7c29f40f59222cee5b8832a52",
132 | "ViewerStateUpdated": "ee640951b5670b559d00b6928e20e4ac29e33d225237f5bdfcb043155f16ef54",
133 | "WebSpeedUpsellQuery": "d8556da659d21dc2c583248c1c617ca20492b64c6948ae4a16256c0848f9c32e",
134 | "WebSubscriptionAnnouncementQuery": "a1b332d7d6816accfccb619e0f0728771ac7c398881fa423051d06551cd0f069",
135 | "WebSubscriptionPaywallModalQuery": "4d248f3aa4fbf68eb57a1bdda52a6dc5f38dd3b1234c01a95d4b17fdfbd922db",
136 | "WebSubscriptionPaywallWrapperQuery": "f84fada22609f5dc5933e7ef1e54001fa5e76871836f268e68ad8df7e202f6ca"
137 | }
--------------------------------------------------------------------------------