├── .githup
├── CODEOWNERS
└── workflows
│ └── python-package.yml
├── .gitignore
├── Dockerfile
├── LICENSE
├── Procfile
├── README.md
├── app.json
├── generate-pyrogram-session-string.py
├── heroku.yml
├── main.py
├── plugins
├── ping.py
├── syninfo.py
└── vc
│ ├── channel.py
│ ├── player.py
│ ├── radio.py
│ └── recorder.py
├── requirements.txt
├── runtime.txt
└── userbot.py
/.githup/CODEOWNERS:
--------------------------------------------------------------------------------
1 | * @zautekm
2 |
--------------------------------------------------------------------------------
/.githup/workflows/python-package.yml:
--------------------------------------------------------------------------------
1 | # This workflow will install Python dependencies, run tests and lint with a variety of Python versions
2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions
3 |
4 | name: Python package
5 |
6 | on: [push, pull_request]
7 |
8 | jobs:
9 | build:
10 |
11 | runs-on: ubuntu-latest
12 | strategy:
13 | matrix:
14 | python-version: ['3.7', '3.8', '3.9']
15 |
16 | steps:
17 | - uses: actions/checkout@v2
18 | - name: Set up Python ${{ matrix.python-version }}
19 | uses: actions/setup-python@v2
20 | with:
21 | python-version: ${{ matrix.python-version }}
22 | - name: Install dependencies
23 | run: |
24 | python -m pip install --upgrade pip
25 | python -m pip install flake8 wheel
26 | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
27 | - name: Lint with flake8
28 | run: |
29 | # stop the build if there are Python syntax errors or undefined names
30 | flake8 . --count --ignore=W503 --select=E,F,W,C --show-source --statistics
31 | flake8 . --count --max-complexity=10 --max-line-length=79 --statistics
32 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # vim
2 | [._]*.sw[a-p]
3 |
4 | # python
5 | /venv/
6 | __pycache__/
7 |
8 | # Pyrogram
9 | /*.py
10 | !/main.py
11 | !/userbot.py
12 | !/generate-pyrogram-session-string.py
13 | /*.ini
14 | /*.session
15 | /*.session-journal
16 | /downloads/
17 |
18 | # pytgcalls
19 | /*.so
20 | /*.log
21 |
22 | # Pycharm
23 | /.idea/
24 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM python:latest
2 |
3 | ENV VIRTUAL_ENV "/venv"
4 | RUN python -m venv $VIRTUAL_ENV
5 | ENV PATH "$VIRTUAL_ENV/bin:$PATH"
6 |
7 | RUN apt-get update && apt-get upgrade -y
8 | RUN apt-get install -y ffmpeg opus-tools bpm-tools
9 | RUN python -m pip install --upgrade pip
10 | RUN python -m pip install wheel
11 | RUN python -m pip install pytgcalls[pyrogram] TgCrypto ffmpeg-python psutil
12 |
13 | RUN wget -q https://github.com/LushaiMusic/VC-UserBot/archive/dev.tar.gz && \
14 | tar xf dev.tar.gz && rm dev.tar.gz
15 |
16 | WORKDIR /VC-UserBot-master
17 | CMD python3 main.py
18 |
19 | # docker build -t tgcalls .
20 | # docker run -it --rm --env-file ./envfile --name VC-UserBot tgcalls
21 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 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 Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 | tgvc-userbot, Telegram Voice Chat Userbot
633 | Copyright (C) 2021 Dash Eclipse
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published by
637 | the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/Procfile:
--------------------------------------------------------------------------------
1 | worker: python3 main.py
2 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Telegram Voice Chat UserBot
2 |
3 | A Telegram UserBot to Play music 🎶 in Voice Chats.
4 |
5 | It's recommended to use an USA number.(if your real number is suspended I'm not responsible.use at your own risks) no grauanty no waranty
6 | Use at your own risks..
7 |
8 | ## Give your 💙
9 |
10 | Before clicking on deploy to heroku just click on fork and star just below
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 | ## How to deploy
23 |
24 | Click the below button to watch the video tutorial on deploying
25 |
26 |
27 |
28 |
29 | ### GET STRING SESSION FROM REPL RUN
30 |
31 | [](https://replit.com/@ZauteKm/generate-pyrogram-session-string#main.py)
32 |
33 | ## Deploy to Heroku
34 |
35 | [](https://heroku.com/deploy?template=https://github.com/LushaiMusic/vc-userbot)
36 |
37 | - Enable the worker after deploy the project to Heroku
38 |
39 | Change the value of `PLUGIN` variable if you want to try other voice chat
40 | plugins.
41 |
42 | ## Introduction
43 |
44 | **Features**
45 |
46 | - Playlist, queue
47 | - Loop one track when there is only one track in the playlist
48 | - Automatically downloads audio for the first two tracks in the playlist to
49 | ensure smooth playing
50 | - Automatically pin the current playing track
51 | - Show current playing position of the audio
52 |
53 | **Plugin**: vc.`player`
54 |
55 | Commands only works in groups, userbot account itself and contacts can use any
56 | commands, all members can use common commands after the userbot join the VC
57 |
58 | 1. Start the userbot, try `!ping`, `!uptime` or `!sysinfo` command to check if
59 | the bot was running
60 | 2. send `!join` to a voice chat enabled group chat from userbot account itself
61 | or its contacts, be sure to make the userbot account as group admin and give
62 | it at least the following permissions:
63 | - Delete messages
64 | - Manage voice chats (optional)
65 | 3. reply to an audio with `/play` to start playing it in the voice chat, every
66 | member of the group can use common commands such like `/play`, `/current`
67 | and `!help` now.
68 | 4. check `!help` for more commands
69 |
70 | **Plugin**: vc.`channel`
71 |
72 | Almost same as `player` plugin but commands only works in Saved Messages,
73 | `!join` takes arguments to be able to join group or channel voice chats.
74 |
75 | **Plugin**: `ping` and `sysinfo`
76 |
77 | Commands only works for userbot account itself and its contacts.
78 |
79 | ## Requirements
80 |
81 | - Python 3.6 or higher
82 | - A
83 | [Telegram API key](https://docs.pyrogram.org/intro/quickstart#enjoy-the-api)
84 | and a Telegram account
85 | - Choose plugins you need, install dependencies which listed above and run
86 | `pip install -U -r requirements.txt` to install Python package dependencies
87 | as well
88 | - [FFmpeg](https://www.ffmpeg.org/)
89 |
90 | ## Run
91 |
92 | Choose one of the two methods and run the userbot with
93 | `python userbot.py`, stop with CTRL+c. The following example assume
94 | that you were going to use `vc.player` and `ping` plugin, replace
95 | `api_id`, `api_hash` to your own value.
96 |
97 | ### Method 1: use config.ini
98 |
99 | Create a `config.ini` file
100 |
101 | ```
102 | [pyrogram]
103 | api_id = 1234567
104 | api_hash = 0123456789abcdef0123456789abcdef
105 |
106 | [plugins]
107 | root = plugins
108 | include =
109 | vc.player
110 | ping
111 | sysinfo
112 | ```
113 |
114 | ### Method 2: write your own userbot.py
115 |
116 | Replace the file content of `userbot.py`
117 |
118 | ```
119 | from pyrogram import Client, idle
120 |
121 | api_id = 1234567
122 | api_hash = "0123456789abcdef0123456789abcdef"
123 |
124 | plugins = dict(
125 | root="plugins",
126 | include=[
127 | "vc.player",
128 | "ping",
129 | "sysinfo"
130 | ]
131 | )
132 |
133 | app = Client("tgvc", api_id, api_hash, plugins=plugins)
134 | app.start()
135 | print('>>> USERBOT STARTED')
136 | idle()
137 | app.stop()
138 | print('\n>>> USERBOT STOPPED')
139 | ```
140 |
141 | ## Notes
142 |
143 | - Read module docstrings of [plugins/](plugins) you are going to use at the
144 | beginning of the file for extra notes
145 |
146 | # License
147 |
148 | AGPL-3.0-or-later
149 |
150 | # Credits :
151 |
152 | This Repo Is Just A Custom Fork Of [callsmusic/tgvc-userbot](https://github.com/callsmusic/tgvc-userbot)
153 |
--------------------------------------------------------------------------------
/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Telegram Voice Chat Music Player UserBot (VC-UserBot)",
3 | "description": "Telegram UserBot to Play Audio in Telegram Voice Chats",
4 | "repository": "https://github.com/LushaiMusic/vc-userbot",
5 | "logo": "https://telegra.ph/file/9f670b987d2b3565a3bcb.jpg",
6 | "keywords": [
7 | "tgvc-userbot",
8 | "telegram",
9 | "userbot",
10 | "voicechat",
11 | "music",
12 | "python",
13 | "pyrogram",
14 | "pytgcalls",
15 | "tgcalls",
16 | "voip"
17 | ],
18 | "env": {
19 | "API_ID": {
20 | "description": "api_id part of your Telegram API Key from my.telegram.org/apps",
21 | "required": true
22 | },
23 | "API_HASH": {
24 | "description": "api_hash part of your Telegram API Key from my.telegram.org/apps",
25 | "required": true
26 | },
27 | "SESSION_NAME": {
28 | "description": "Session string, read the README to learn how to export it with Pyrogram",
29 | "required": true
30 | },
31 | "PLUGIN": {
32 | "description": "Voice Chat Smart Plugin to enable, must be one of: player/channel/recorder/radio",
33 | "value": "player",
34 | "required": true
35 | }
36 | },
37 | "buildpacks": [
38 | {
39 | "url": "https://github.com/jonathanong/heroku-buildpack-ffmpeg-latest"
40 | },
41 | {
42 | "url": "heroku/python"
43 | }
44 | ]
45 | }
46 |
--------------------------------------------------------------------------------
/generate-pyrogram-session-string.py:
--------------------------------------------------------------------------------
1 | """Generate Pyrogram Session String and send it to
2 | Saved Messages of your Telegram account
3 |
4 | requirements:
5 | - Pyrogram
6 | - TgCrypto
7 |
8 | Get your Telegram API Key from:
9 | https://my.telegram.org/apps
10 | """
11 | import asyncio
12 | from pyrogram import Client
13 |
14 |
15 | async def main():
16 | api_id = int(input("API ID: "))
17 | api_hash = input("API HASH: ")
18 | async with Client(":memory:", api_id=api_id, api_hash=api_hash) as app:
19 | await app.send_message(
20 | "me",
21 | "**Pyrogram Session String**:\n\n"
22 | f"`{await app.export_session_string()}`"
23 | )
24 | print(
25 | "Done, your Pyrogram session string has been sent to "
26 | "Saved Messages of your Telegram account!"
27 | )
28 |
29 | if __name__ == "__main__":
30 | loop = asyncio.get_event_loop()
31 | loop.run_until_complete(main())
32 |
--------------------------------------------------------------------------------
/heroku.yml:
--------------------------------------------------------------------------------
1 | build:
2 | docker:
3 | worker: Dockerfile
4 |
--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
1 | from os import environ
2 |
3 | # import logging
4 | from pyrogram import Client, idle
5 |
6 | API_ID = int(environ["API_ID"])
7 | API_HASH = environ["API_HASH"]
8 | SESSION_NAME = environ["SESSION_NAME"]
9 |
10 | PLUGINS = dict(
11 | root="plugins",
12 | include=[
13 | "vc." + environ["PLUGIN"],
14 | "ping",
15 | "sysinfo"
16 | ]
17 | )
18 |
19 | app = Client(SESSION_NAME, API_ID, API_HASH, plugins=PLUGINS)
20 | # logging.basicConfig(level=logging.INFO)
21 | app.start()
22 | print('>>> USERBOT STARTED')
23 | idle()
24 | app.stop()
25 | print('\n>>> USERBOT STOPPED')
26 |
--------------------------------------------------------------------------------
/plugins/ping.py:
--------------------------------------------------------------------------------
1 | from datetime import datetime
2 | from time import time
3 |
4 | from pyrogram import Client, filters, emoji
5 | from pyrogram.types import Message
6 |
7 | START_TIME = datetime.utcnow()
8 | START_TIME_ISO = START_TIME.replace(microsecond=0).isoformat()
9 | TIME_DURATION_UNITS = (
10 | ('week', 60 * 60 * 24 * 7),
11 | ('day', 60 * 60 * 24),
12 | ('hour', 60 * 60),
13 | ('min', 60),
14 | ('sec', 1)
15 | )
16 |
17 | self_or_contact_filter = filters.create(
18 | lambda _, __, message:
19 | (message.from_user and message.from_user.is_contact) or message.outgoing
20 | )
21 |
22 |
23 | # https://gist.github.com/borgstrom/936ca741e885a1438c374824efb038b3
24 | async def _human_time_duration(seconds):
25 | if seconds == 0:
26 | return 'inf'
27 | parts = []
28 | for unit, div in TIME_DURATION_UNITS:
29 | amount, seconds = divmod(int(seconds), div)
30 | if amount > 0:
31 | parts.append('{} {}{}'
32 | .format(amount, unit, "" if amount == 1 else "s"))
33 | return ', '.join(parts)
34 |
35 |
36 | @Client.on_message(filters.text
37 | & self_or_contact_filter
38 | & ~filters.edited
39 | & ~filters.via_bot
40 | & filters.regex("^!ping$"))
41 | async def ping_pong(_, m: Message):
42 | """Reply ping with pong and delete both messages"""
43 | start = time()
44 | m_reply = await m.reply_text("...")
45 | delta_ping = time() - start
46 | await m_reply.edit_text(
47 | f"{emoji.ROBOT} ping: `{delta_ping * 1000:.3f} ms`"
48 | )
49 |
50 |
51 | @Client.on_message(filters.text
52 | & self_or_contact_filter
53 | & ~filters.edited
54 | & ~filters.via_bot
55 | & filters.regex("^!uptime$"))
56 | async def get_uptime(_, m: Message):
57 | """/uptime Reply with readable uptime and ISO 8601 start time"""
58 | current_time = datetime.utcnow()
59 | uptime_sec = (current_time - START_TIME).total_seconds()
60 | uptime = await _human_time_duration(int(uptime_sec))
61 | await m.reply_text(
62 | f"{emoji.ROBOT}\n"
63 | f"- uptime: `{uptime}`\n"
64 | f"- start time: `{START_TIME_ISO}`"
65 | )
66 |
--------------------------------------------------------------------------------
/plugins/syninfo.py:
--------------------------------------------------------------------------------
1 | import psutil
2 | # noinspection PyProtectedMember
3 | from psutil._common import bytes2human
4 | from pyrogram import Client, filters
5 |
6 | self_or_contact_filter = filters.create(
7 | lambda _, __, message:
8 | (message.from_user and message.from_user.is_contact) or message.outgoing
9 | )
10 |
11 |
12 | async def generate_sysinfo(workdir):
13 | # uptime
14 | info = {
15 | 'boot': (datetime.fromtimestamp(psutil.boot_time())
16 | .strftime("%Y-%m-%d %H:%M:%S"))
17 | }
18 | # CPU
19 | cpu_freq = psutil.cpu_freq().current
20 | if cpu_freq >= 1000:
21 | cpu_freq = f"{round(cpu_freq / 1000, 2)}GHz"
22 | else:
23 | cpu_freq = f"{round(cpu_freq, 2)}MHz"
24 | info['cpu'] = (
25 | f"{psutil.cpu_percent(interval=1)}% "
26 | f"({psutil.cpu_count()}) "
27 | f"{cpu_freq}"
28 | )
29 | # Memory
30 | vm = psutil.virtual_memory()
31 | sm = psutil.swap_memory()
32 | info['ram'] = (f"{bytes2human(vm.total)}, "
33 | f"{bytes2human(vm.available)} available")
34 | info['swap'] = f"{bytes2human(sm.total)}, {sm.percent}%"
35 | # Disks
36 | du = psutil.disk_usage(workdir)
37 | dio = psutil.disk_io_counters()
38 | info['disk'] = (f"{bytes2human(du.used)} / {bytes2human(du.total)} "
39 | f"({du.percent}%)")
40 | if dio:
41 | info['disk io'] = (f"R {bytes2human(dio.read_bytes)} | "
42 | f"W {bytes2human(dio.write_bytes)}")
43 | # Network
44 | nio = psutil.net_io_counters()
45 | info['net io'] = (f"TX {bytes2human(nio.bytes_sent)} | "
46 | f"RX {bytes2human(nio.bytes_recv)}")
47 | # Sensors
48 | sensors_temperatures = psutil.sensors_temperatures()
49 | if sensors_temperatures:
50 | temperatures_list = [
51 | x.current
52 | for x in sensors_temperatures['coretemp']
53 | ]
54 | temperatures = sum(temperatures_list) / len(temperatures_list)
55 | info['temp'] = f"{temperatures}\u00b0C"
56 | info = {f"{key}:": value for (key, value) in info.items()}
57 | max_len = max(len(x) for x in info)
58 | return ("```"
59 | + "\n".join([f"{x:<{max_len}} {y}" for x, y in info.items()])
60 | + "```")
61 |
62 |
63 | @Client.on_message(filters.group
64 | & filters.text
65 | & self_or_contact_filter
66 | & ~filters.edited
67 | & ~filters.via_bot
68 | & filters.regex("^!sysinfo$"))
69 | async def get_sysinfo(client, m):
70 | response = "**System Information**:\n"
71 | m_reply = await m.reply_text(f"{response}`...`")
72 | response += await generate_sysinfo(client.workdir)
73 | await m_reply.edit_text(response)
74 |
--------------------------------------------------------------------------------
/plugins/vc/channel.py:
--------------------------------------------------------------------------------
1 | """
2 | tg-vc-userbot, Telegram Voice Chat Userbot
3 | Copyright (C) 2021 Zaute Km
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU Affero General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU Affero General Public License for more details.
14 |
15 | You should have received a copy of the GNU Affero General Public License
16 | along with this program. If not, see .
17 |
18 | Play and Control Audio playing in Telegram channels Voice Chat
19 |
20 | Dependencies:
21 | - ffmpeg
22 | """
23 | import asyncio
24 | import os
25 | from datetime import datetime, timedelta
26 | from typing import Union
27 |
28 | # noinspection PyPackageRequirements
29 | import ffmpeg
30 | from pyrogram import Client, filters, emoji
31 | from pyrogram.methods.messages.download_media import DEFAULT_DOWNLOAD_DIR
32 | from pyrogram.types import Message
33 | from pytgcalls import GroupCall
34 |
35 | DELETE_DELAY = 8
36 | DURATION_AUTOPLAY_MIN = 600
37 | DURATION_PLAY_HOUR = 10
38 |
39 | USERBOT_HELP = f"""{emoji.LABEL} **Commands**:
40 |
41 | \u2022 **/play** reply with an audio to play/queue it, or show playlist
42 | \u2022 **/current** show current playing time of current track
43 | \u2022 **/repo** show git repository of the userbot
44 | \u2022 `!help` show help for commands
45 |
46 | \u2022 `!skip` `[n] ...` skip current or n where n >= 2
47 | \u2022 `!join` ` [join_as] [invite_hash]` join group/channel VC
48 | \u2022 `!leave` leave current voice chat
49 | \u2022 `!vc` check which VC is joined
50 | \u2022 `!stop` stop playing
51 | \u2022 `!replay` play from the beginning
52 | \u2022 `!clean` remove unused RAW PCM files
53 | \u2022 `!pause` pause playing
54 | \u2022 `!resume` resume playing
55 | \u2022 `!mute` mute the VC userbot
56 | \u2022 `!unmute` unmute the VC userbot
57 | """
58 |
59 | USERBOT_REPO = f"""{emoji.ROBOT} **Telegram Voice Chat UserBot**
60 |
61 | - Repository: [GitHub](https://github.com/lushaimusic/tg-vc-userbot)
62 | - License: AGPL-3.0-or-later"""
63 |
64 | # - Pyrogram filters
65 |
66 | # self_or_contact_pm_filter = filters.create(
67 | # lambda _, __, m:
68 | # m.chat and m.chat.type == "private"
69 | # and m.from_user and (m.from_user.is_contact or m.from_user.is_self)
70 | # )
71 |
72 | main_filter = (filters.chat("me")
73 | & filters.text
74 | & ~filters.edited
75 | & ~filters.via_bot)
76 |
77 |
78 | # - class
79 |
80 | class MusicPlayer(object):
81 | def __init__(self):
82 | self.group_call = GroupCall(None, path_to_log_file='')
83 | self.chat_id = None
84 | self.start_time = None
85 | self.playlist = []
86 | self.msg = {}
87 |
88 | async def update_start_time(self, reset=False):
89 | self.start_time = (
90 | None if reset
91 | else datetime.utcnow().replace(microsecond=0)
92 | )
93 |
94 | async def send_playlist(self):
95 | playlist = self.playlist
96 | if not playlist:
97 | pl = f"{emoji.NO_ENTRY} empty playlist"
98 | else:
99 | if len(playlist) == 1:
100 | pl = f"{emoji.REPEAT_SINGLE_BUTTON} **Playlist**:\n"
101 | else:
102 | pl = f"{emoji.PLAY_BUTTON} **Playlist**:\n"
103 | pl += "\n".join([
104 | f"**{i}**. **[{x.audio.title}]({x.link})**"
105 | for i, x in enumerate(playlist)
106 | ])
107 | if mp.msg.get('playlist') is not None:
108 | await mp.msg['playlist'].delete()
109 | mp.msg['playlist'] = await mp.group_call.client.send_message("me", pl)
110 |
111 |
112 | mp = MusicPlayer()
113 |
114 |
115 | # - pytgcalls handlers
116 |
117 |
118 | @mp.group_call.on_network_status_changed
119 | async def network_status_changed_handler(gc: GroupCall, is_connected: bool):
120 | if is_connected:
121 | mp.chat_id = int("-100" + str(gc.full_chat.id))
122 | await mp.group_call.client.send_message(
123 | "me",
124 | f"{emoji.CHECK_MARK_BUTTON} joined the voice chat"
125 | )
126 | else:
127 | mp.chat_id = None
128 | await mp.group_call.client.send_message(
129 | "me",
130 | f"{emoji.CROSS_MARK_BUTTON} left the voice chat"
131 | )
132 |
133 |
134 | @mp.group_call.on_playout_ended
135 | async def playout_ended_handler(_, __):
136 | await skip_current_playing()
137 |
138 |
139 | # - Pyrogram handers
140 |
141 | @Client.on_message(main_filter
142 | & filters.command("join", prefixes="!"))
143 | async def join_voice_chat(client, m: Message):
144 | command = m.command
145 | len_command = len(command)
146 | if 2 <= len_command <= 4:
147 | channel = await get_id(command[1])
148 | join_as = await get_id(command[2]) if len_command >= 3 else None
149 | invite_hash = command[3] if len_command == 4 else None
150 | group_call = mp.group_call
151 | group_call.client = client
152 | if group_call.is_connected:
153 | text = f"{emoji.ROBOT} already joined a voice chat"
154 | else:
155 | await group_call.start(channel, join_as=join_as,
156 | invite_hash=invite_hash)
157 | # text = "Status will be sent to Saved Messages"
158 | return
159 | else:
160 | text = "**Usage**: `!join [join_as] [invite_hash]`"
161 | await m.reply_text(text, quote=True, parse_mode="md")
162 |
163 |
164 | @Client.on_message(main_filter
165 | & filters.regex("^!vc$"))
166 | async def list_voice_chat(client, m: Message):
167 | group_call = mp.group_call
168 | if group_call.is_connected:
169 | chat_id = int("-100" + str(group_call.full_chat.id))
170 | chat = await client.get_chat(chat_id)
171 | await m.reply_text(
172 | f"{emoji.MUSICAL_NOTES} **currently in the voice chat**:\n"
173 | f"- **{chat.title}**",
174 | quote=True
175 | )
176 | else:
177 | await m.reply_text(f"{emoji.NO_ENTRY} didn't join any voice chat yet",
178 | quote=True)
179 |
180 |
181 | @Client.on_message(main_filter
182 | & filters.regex("^!leave$"))
183 | async def leave_voice_chat(_, m: Message):
184 | group_call = mp.group_call
185 | mp.playlist.clear()
186 | group_call.input_filename = ''
187 | await group_call.stop()
188 | await m.delete()
189 |
190 |
191 | @Client.on_message(
192 | filters.chat("me")
193 | & ~filters.edited
194 | & (filters.regex("^(\\/|!)play$") | filters.audio)
195 | )
196 | async def play_track(client, m: Message):
197 | group_call = mp.group_call
198 | playlist = mp.playlist
199 | # check audio
200 | if m.audio:
201 | if m.audio.duration > (DURATION_AUTOPLAY_MIN * 600):
202 | reply = await m.reply_text(
203 | f"{emoji.ROBOT} audio which duration longer than "
204 | f"{str(DURATION_AUTOPLAY_MIN)} min won't be automatically "
205 | "added to playlist",
206 | quote=True
207 | )
208 | await _delay_delete_messages((reply,), DELETE_DELAY)
209 | return
210 | m_audio = m
211 | elif m.reply_to_message and m.reply_to_message.audio:
212 | m_audio = m.reply_to_message
213 | if m_audio.audio.duration > (DURATION_PLAY_HOUR * 600 * 600):
214 | reply = await m.reply_text(
215 | f"{emoji.ROBOT} audio which duration longer than "
216 | f"{str(DURATION_PLAY_HOUR)} hours won't be added to playlist",
217 | quote=True
218 | )
219 | await _delay_delete_messages((reply,), DELETE_DELAY)
220 | return
221 | else:
222 | await mp.send_playlist()
223 | await m.delete()
224 | return
225 | # check already added
226 | if playlist and playlist[-1].audio.file_unique_id \
227 | == m_audio.audio.file_unique_id:
228 | reply = await m.reply_text(f"{emoji.ROBOT} already added", quote=True)
229 | await _delay_delete_messages((reply, m), DELETE_DELAY)
230 | return
231 | # add to playlist
232 | playlist.append(m_audio)
233 | if len(playlist) == 1:
234 | m_status = await m.reply_text(
235 | f"{emoji.INBOX_TRAY} downloading and transcoding...",
236 | quote=True
237 | )
238 | await download_audio(playlist[0])
239 | group_call.input_filename = os.path.join(
240 | client.workdir,
241 | DEFAULT_DOWNLOAD_DIR,
242 | f"{playlist[0].audio.file_unique_id}.raw"
243 | )
244 | await mp.update_start_time()
245 | await m_status.delete()
246 | print(f"- START PLAYING: {playlist[0].audio.title}")
247 | await mp.send_playlist()
248 | for track in playlist[:2]:
249 | await download_audio(track)
250 | if not m.audio:
251 | await m.delete()
252 |
253 |
254 | @Client.on_message(main_filter
255 | & filters.regex("^(\\/|!)current$"))
256 | async def show_current_playing_time(_, m: Message):
257 | start_time = mp.start_time
258 | playlist = mp.playlist
259 | if not start_time:
260 | reply = await m.reply_text(f"{emoji.PLAY_BUTTON} unknown", quote=True)
261 | await _delay_delete_messages((reply, m), DELETE_DELAY)
262 | return
263 | utcnow = datetime.utcnow().replace(microsecond=0)
264 | if mp.msg.get('current') is not None:
265 | await mp.msg['current'].delete()
266 | mp.msg['current'] = await playlist[0].reply_text(
267 | f"{emoji.PLAY_BUTTON} {utcnow - start_time} / "
268 | f"{timedelta(seconds=playlist[0].audio.duration)}",
269 | quote=True,
270 | disable_notification=True
271 | )
272 | await m.delete()
273 |
274 |
275 | @Client.on_message(main_filter
276 | & filters.regex("^(\\/|!)help$"))
277 | async def show_help(_, m: Message):
278 | if mp.msg.get('help') is not None:
279 | await mp.msg['help'].delete()
280 | mp.msg['help'] = await m.reply_text(
281 | USERBOT_HELP,
282 | quote=True,
283 | parse_mode="md"
284 | )
285 | await m.delete()
286 |
287 |
288 | @Client.on_message(main_filter
289 | & filters.command("skip", prefixes="!"))
290 | async def skip_track(_, m: Message):
291 | playlist = mp.playlist
292 | if len(m.command) == 1:
293 | await skip_current_playing()
294 | else:
295 | try:
296 | items = list(dict.fromkeys(m.command[1:]))
297 | items = [int(x) for x in items if x.isdigit()]
298 | items.sort(reverse=True)
299 | text = []
300 | for i in items:
301 | if 2 <= i <= (len(playlist) - 1):
302 | audio = f"[{playlist[i].audio.title}]({playlist[i].link})"
303 | playlist.pop(i)
304 | text.append(f"{emoji.WASTEBASKET} {i}. **{audio}**")
305 | else:
306 | text.append(f"{emoji.CROSS_MARK} {i}")
307 | reply = await m.reply_text("\n".join(text), quote=True)
308 | await mp.send_playlist()
309 | except (ValueError, TypeError):
310 | reply = await m.reply_text(f"{emoji.NO_ENTRY} invalid input",
311 | quote=True,
312 | disable_web_page_preview=True)
313 | await _delay_delete_messages((reply, m), DELETE_DELAY)
314 |
315 |
316 | @Client.on_message(main_filter
317 | & filters.regex("^!stop$"))
318 | async def stop_playing(_, m: Message):
319 | group_call = mp.group_call
320 | group_call.stop_playout()
321 | reply = await m.reply_text(
322 | f"{emoji.STOP_BUTTON} stopped playing",
323 | quote=True
324 | )
325 | await mp.update_start_time(reset=True)
326 | mp.playlist.clear()
327 | await _delay_delete_messages((reply, m), DELETE_DELAY)
328 |
329 |
330 | @Client.on_message(main_filter
331 | & filters.regex("^!replay$"))
332 | async def restart_playing(_, m: Message):
333 | group_call = mp.group_call
334 | if not mp.playlist:
335 | return
336 | group_call.restart_playout()
337 | await mp.update_start_time()
338 | reply = await m.reply_text(
339 | f"{emoji.COUNTERCLOCKWISE_ARROWS_BUTTON} "
340 | "playing from the beginning...",
341 | quote=True
342 | )
343 | await _delay_delete_messages((reply, m), DELETE_DELAY)
344 |
345 |
346 | @Client.on_message(main_filter
347 | & filters.regex("^!pause"))
348 | async def pause_playing(_, m: Message):
349 | mp.group_call.pause_playout()
350 | await mp.update_start_time(reset=True)
351 | reply = await m.reply_text(f"{emoji.PLAY_OR_PAUSE_BUTTON} paused",
352 | quote=True)
353 | mp.msg['pause'] = reply
354 | await m.delete()
355 |
356 |
357 | @Client.on_message(main_filter
358 | & filters.regex("^!resume"))
359 | async def resume_playing(_, m: Message):
360 | mp.group_call.resume_playout()
361 | reply = await m.reply_text(f"{emoji.PLAY_OR_PAUSE_BUTTON} resumed",
362 | quote=True)
363 | if mp.msg.get('pause') is not None:
364 | await mp.msg['pause'].delete()
365 | await m.delete()
366 | await _delay_delete_messages((reply,), DELETE_DELAY)
367 |
368 |
369 | @Client.on_message(main_filter
370 | & filters.regex("^!clean$"))
371 | async def clean_raw_pcm(client, m: Message):
372 | download_dir = os.path.join(client.workdir, DEFAULT_DOWNLOAD_DIR)
373 | all_fn: list[str] = os.listdir(download_dir)
374 | for track in mp.playlist[:2]:
375 | track_fn = f"{track.audio.file_unique_id}.raw"
376 | if track_fn in all_fn:
377 | all_fn.remove(track_fn)
378 | count = 0
379 | if all_fn:
380 | for fn in all_fn:
381 | if fn.endswith(".raw"):
382 | count += 1
383 | os.remove(os.path.join(download_dir, fn))
384 | reply = await m.reply_text(
385 | f"{emoji.WASTEBASKET} cleaned {count} files",
386 | quote=True
387 | )
388 | await _delay_delete_messages((reply, m), DELETE_DELAY)
389 |
390 |
391 | @Client.on_message(main_filter
392 | & filters.regex("^!mute$"))
393 | async def mute(_, m: Message):
394 | group_call = mp.group_call
395 | group_call.set_is_mute(True)
396 | reply = await m.reply_text(f"{emoji.MUTED_SPEAKER} muted", quote=True)
397 | await _delay_delete_messages((reply, m), DELETE_DELAY)
398 |
399 |
400 | @Client.on_message(main_filter
401 | & filters.regex("^!unmute$"))
402 | async def unmute(_, m: Message):
403 | group_call = mp.group_call
404 | group_call.set_is_mute(False)
405 | reply = await m.reply_text(
406 | f"{emoji.SPEAKER_MEDIUM_VOLUME} unmuted",
407 | quote=True
408 | )
409 | await _delay_delete_messages((reply, m), DELETE_DELAY)
410 |
411 |
412 | @Client.on_message(main_filter
413 | & filters.regex("^(\\/|!)repo$"))
414 | async def show_repository(_, m: Message):
415 | if mp.msg.get('repo') is not None:
416 | await mp.msg['repo'].delete()
417 | mp.msg['repo'] = await m.reply_text(
418 | USERBOT_REPO,
419 | disable_web_page_preview=True,
420 | quote=False
421 | )
422 | await m.delete()
423 |
424 |
425 | # - Other functions
426 |
427 | async def get_id(channel: str) -> Union[str, int]:
428 | return int(channel) if str.isdigit(channel) else channel
429 |
430 |
431 | async def skip_current_playing():
432 | group_call = mp.group_call
433 | playlist = mp.playlist
434 | if not playlist:
435 | return
436 | if len(playlist) == 1:
437 | await mp.update_start_time()
438 | return
439 | client = group_call.client
440 | download_dir = os.path.join(client.workdir, DEFAULT_DOWNLOAD_DIR)
441 | group_call.input_filename = os.path.join(
442 | download_dir,
443 | f"{playlist[1].audio.file_unique_id}.raw"
444 | )
445 | await mp.update_start_time()
446 | # remove old track from playlist
447 | old_track = playlist.pop(0)
448 | print(f"- START PLAYING: {playlist[0].audio.title}")
449 | await mp.send_playlist()
450 | os.remove(os.path.join(
451 | download_dir,
452 | f"{old_track.audio.file_unique_id}.raw")
453 | )
454 | if len(playlist) == 1:
455 | return
456 | await download_audio(playlist[1])
457 |
458 |
459 | async def download_audio(m: Message):
460 | group_call = mp.group_call
461 | client = group_call.client
462 | raw_file = os.path.join(client.workdir, DEFAULT_DOWNLOAD_DIR,
463 | f"{m.audio.file_unique_id}.raw")
464 | if not os.path.isfile(raw_file):
465 | original_file = await m.download()
466 | ffmpeg.input(original_file).output(
467 | raw_file,
468 | format='s16le',
469 | acodec='pcm_s16le',
470 | ac=2,
471 | ar='48k',
472 | loglevel='error'
473 | ).overwrite_output().run()
474 | os.remove(original_file)
475 |
476 |
477 | async def _delay_delete_messages(messages: tuple, delay: int):
478 | await asyncio.sleep(delay)
479 | for m in messages:
480 | await m.delete()
481 |
--------------------------------------------------------------------------------
/plugins/vc/player.py:
--------------------------------------------------------------------------------
1 | """
2 | VC-UserBot, Telegram Voice Chat Userbot
3 | Copyright (C) 2021 Zaute Km
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU Affero General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU Affero General Public License for more details.
14 |
15 | You should have received a copy of the GNU Affero General Public License
16 | along with this program. If not, see .
17 |
18 | Play and Control Audio playing in Telegram Voice Chat
19 |
20 | Dependencies:
21 | - ffmpeg
22 |
23 | Required group admin permissions:
24 | - Delete messages
25 | - Manage voice chats (optional)
26 |
27 | How to use:
28 | - Start the userbot
29 | - send !join to a voice chat enabled group chat
30 | from userbot account itself or its contacts
31 | - reply to an audio with /play to start playing
32 | it in the voice chat, every member of the group
33 | can use the !play command now
34 | - check !help for more commands
35 | """
36 | import asyncio
37 | import os
38 | from datetime import datetime, timedelta
39 |
40 | # noinspection PyPackageRequirements
41 | import ffmpeg
42 | from pyrogram import Client, filters, emoji
43 | from pyrogram.methods.messages.download_media import DEFAULT_DOWNLOAD_DIR
44 | from pyrogram.types import Message
45 | from pyrogram.utils import MAX_CHANNEL_ID
46 | from pytgcalls import GroupCallFactory, GroupCallFileAction
47 |
48 | DELETE_DELAY = 8
49 | DURATION_AUTOPLAY_MIN = 10
50 | DURATION_PLAY_HOUR = 3
51 |
52 | USERBOT_HELP = f"""{emoji.LABEL} **Common Commands**:
53 | __available to group members of current voice chat__
54 | __starts with / (slash) or ! (exclamation mark)__
55 |
56 | \u2022 **/play** reply with an audio to play/queue it, or show playlist
57 | \u2022 **/current** show current playing time of current track
58 | \u2022 **/repo** show git repository of the userbot
59 | \u2022 `!help` show help for commands
60 |
61 |
62 | {emoji.LABEL} **Admin Commands**:
63 | __available to userbot account itself and its contacts__
64 | __starts with ! (exclamation mark)__
65 |
66 | \u2022 `!skip` [n] ... skip current or n where n >= 2
67 | \u2022 `!join` join voice chat of current group
68 | \u2022 `!leave` leave current voice chat
69 | \u2022 `!vc` check which VC is joined
70 | \u2022 `!stop` stop playing
71 | \u2022 `!replay` play from the beginning
72 | \u2022 `!clean` remove unused RAW PCM files
73 | \u2022 `!pause` pause playing
74 | \u2022 `!resume` resume playing
75 | \u2022 `!mute` mute the VC userbot
76 | \u2022 `!unmute` unmute the VC userbot
77 | """
78 |
79 | USERBOT_REPO = f"""{emoji.ROBOT} **Telegram Voice Chat UserBot**
80 |
81 | - Repository: [GitHub](https://github.com/LushaiMusic/VC-UserBot)
82 | - License: AGPL-3.0-or-later"""
83 |
84 | # - Pyrogram filters
85 |
86 | main_filter = (filters.group
87 | & filters.text
88 | & ~filters.edited
89 | & ~filters.via_bot)
90 | self_or_contact_filter = filters.create(
91 | lambda _, __, message:
92 | (message.from_user and message.from_user.is_contact) or message.outgoing
93 | )
94 |
95 |
96 | async def current_vc_filter(_, __, m: Message):
97 | group_call = mp.group_call
98 | if not (group_call and group_call.is_connected):
99 | return False
100 | chat_id = int("-100" + str(group_call.full_chat.id))
101 | if m.chat.id == chat_id:
102 | return True
103 | return False
104 |
105 |
106 | current_vc = filters.create(current_vc_filter)
107 |
108 |
109 | # - class
110 |
111 |
112 | class MusicPlayer(object):
113 | def __init__(self):
114 | self.group_call = None
115 | self.client = None
116 | self.chat_id = None
117 | self.start_time = None
118 | self.playlist = []
119 | self.msg = {}
120 |
121 | async def update_start_time(self, reset=False):
122 | self.start_time = (
123 | None if reset
124 | else datetime.utcnow().replace(microsecond=0)
125 | )
126 |
127 | async def send_playlist(self):
128 | playlist = self.playlist
129 | if not playlist:
130 | pl = f"{emoji.NO_ENTRY} empty playlist"
131 | else:
132 | if len(playlist) == 1:
133 | pl = f"{emoji.REPEAT_SINGLE_BUTTON} **Playlist**:\n"
134 | else:
135 | pl = f"{emoji.PLAY_BUTTON} **Playlist**:\n"
136 | pl += "\n".join([
137 | f"**{i}**. **[{x.audio.title}]({x.link})**"
138 | for i, x in enumerate(playlist)
139 | ])
140 | if mp.msg.get('playlist') is not None:
141 | await mp.msg['playlist'].delete()
142 | mp.msg['playlist'] = await send_text(pl)
143 |
144 |
145 | mp = MusicPlayer()
146 |
147 |
148 | # - pytgcalls handlers
149 |
150 |
151 | async def network_status_changed_handler(context, is_connected: bool):
152 | if is_connected:
153 | mp.chat_id = MAX_CHANNEL_ID - context.full_chat.id
154 | await send_text(f"{emoji.CHECK_MARK_BUTTON} joined the voice chat")
155 | else:
156 | await send_text(f"{emoji.CROSS_MARK_BUTTON} left the voice chat")
157 | mp.chat_id = None
158 |
159 |
160 | async def playout_ended_handler(_, __):
161 | await skip_current_playing()
162 |
163 |
164 | # - Pyrogram handlers
165 |
166 |
167 | @Client.on_message(
168 | filters.group
169 | & ~filters.edited
170 | & current_vc
171 | & (filters.regex("^(\\/|!)play$") | filters.audio)
172 | )
173 | async def play_track(client, m: Message):
174 | group_call = mp.group_call
175 | playlist = mp.playlist
176 | # check audio
177 | if m.audio:
178 | if m.audio.duration > (DURATION_AUTOPLAY_MIN * 60):
179 | reply = await m.reply_text(
180 | f"{emoji.ROBOT} audio which duration longer than "
181 | f"{str(DURATION_AUTOPLAY_MIN)} min won't be automatically "
182 | "added to playlist"
183 | )
184 | await _delay_delete_messages((reply,), DELETE_DELAY)
185 | return
186 | m_audio = m
187 | elif m.reply_to_message and m.reply_to_message.audio:
188 | m_audio = m.reply_to_message
189 | if m_audio.audio.duration > (DURATION_PLAY_HOUR * 60 * 60):
190 | reply = await m.reply_text(
191 | f"{emoji.ROBOT} audio which duration longer than "
192 | f"{str(DURATION_PLAY_HOUR)} hours won't be added to playlist"
193 | )
194 | await _delay_delete_messages((reply,), DELETE_DELAY)
195 | return
196 | else:
197 | await mp.send_playlist()
198 | await m.delete()
199 | return
200 | # check already added
201 | if playlist and playlist[-1].audio.file_unique_id \
202 | == m_audio.audio.file_unique_id:
203 | reply = await m.reply_text(f"{emoji.ROBOT} already added")
204 | await _delay_delete_messages((reply, m), DELETE_DELAY)
205 | return
206 | # add to playlist
207 | playlist.append(m_audio)
208 | if len(playlist) == 1:
209 | m_status = await m.reply_text(
210 | f"{emoji.INBOX_TRAY} downloading and transcoding..."
211 | )
212 | await download_audio(playlist[0])
213 | group_call.input_filename = os.path.join(
214 | client.workdir,
215 | DEFAULT_DOWNLOAD_DIR,
216 | f"{playlist[0].audio.file_unique_id}.raw"
217 | )
218 | await mp.update_start_time()
219 | await m_status.delete()
220 | print(f"- START PLAYING: {playlist[0].audio.title}")
221 | await mp.send_playlist()
222 | for track in playlist[:2]:
223 | await download_audio(track)
224 | if not m.audio:
225 | await m.delete()
226 |
227 |
228 | @Client.on_message(main_filter
229 | & current_vc
230 | & filters.regex("^(\\/|!)current$"))
231 | async def show_current_playing_time(_, m: Message):
232 | start_time = mp.start_time
233 | playlist = mp.playlist
234 | if not start_time:
235 | reply = await m.reply_text(f"{emoji.PLAY_BUTTON} unknown")
236 | await _delay_delete_messages((reply, m), DELETE_DELAY)
237 | return
238 | utcnow = datetime.utcnow().replace(microsecond=0)
239 | if mp.msg.get('current') is not None:
240 | await mp.msg['current'].delete()
241 | mp.msg['current'] = await playlist[0].reply_text(
242 | f"{emoji.PLAY_BUTTON} {utcnow - start_time} / "
243 | f"{timedelta(seconds=playlist[0].audio.duration)}",
244 | disable_notification=True
245 | )
246 | await m.delete()
247 |
248 |
249 | @Client.on_message(main_filter
250 | & (self_or_contact_filter | current_vc)
251 | & filters.regex("^(\\/|!)help$"))
252 | async def show_help(_, m: Message):
253 | if mp.msg.get('help') is not None:
254 | await mp.msg['help'].delete()
255 | mp.msg['help'] = await m.reply_text(USERBOT_HELP, quote=False)
256 | await m.delete()
257 |
258 |
259 | @Client.on_message(main_filter
260 | & self_or_contact_filter
261 | & current_vc
262 | & filters.command("skip", prefixes="!"))
263 | async def skip_track(_, m: Message):
264 | playlist = mp.playlist
265 | if len(m.command) == 1:
266 | await skip_current_playing()
267 | else:
268 | try:
269 | items = list(dict.fromkeys(m.command[1:]))
270 | items = [int(x) for x in items if x.isdigit()]
271 | items.sort(reverse=True)
272 | text = []
273 | for i in items:
274 | if 2 <= i <= (len(playlist) - 1):
275 | audio = f"[{playlist[i].audio.title}]({playlist[i].link})"
276 | playlist.pop(i)
277 | text.append(f"{emoji.WASTEBASKET} {i}. **{audio}**")
278 | else:
279 | text.append(f"{emoji.CROSS_MARK} {i}")
280 | reply = await m.reply_text(
281 | "\n".join(text),
282 | disable_web_page_preview=True
283 | )
284 | await mp.send_playlist()
285 | except (ValueError, TypeError):
286 | reply = await m.reply_text(f"{emoji.NO_ENTRY} invalid input",
287 | disable_web_page_preview=True)
288 | await _delay_delete_messages((reply, m), DELETE_DELAY)
289 |
290 |
291 | @Client.on_message(main_filter
292 | & self_or_contact_filter
293 | & filters.regex("^!join$"))
294 | async def join_group_call(client, m: Message):
295 | group_call = mp.group_call
296 | if not group_call:
297 | mp.group_call = GroupCallFactory(client).get_file_group_call()
298 | mp.group_call.add_handler(network_status_changed_handler,
299 | GroupCallFileAction.NETWORK_STATUS_CHANGED)
300 | mp.group_call.add_handler(playout_ended_handler,
301 | GroupCallFileAction.PLAYOUT_ENDED)
302 | await mp.group_call.start(m.chat.id)
303 | await m.delete()
304 | if group_call and group_call.is_connected:
305 | await m.reply_text(f"{emoji.ROBOT} already joined a voice chat")
306 |
307 |
308 | @Client.on_message(main_filter
309 | & self_or_contact_filter
310 | & current_vc
311 | & filters.regex("^!leave$"))
312 | async def leave_voice_chat(_, m: Message):
313 | group_call = mp.group_call
314 | mp.playlist.clear()
315 | group_call.input_filename = ''
316 | await group_call.stop()
317 | await m.delete()
318 |
319 |
320 | @Client.on_message(main_filter
321 | & self_or_contact_filter
322 | & filters.regex("^!vc$"))
323 | async def list_voice_chat(client, m: Message):
324 | group_call = mp.group_call
325 | if group_call and group_call.is_connected:
326 | chat_id = int("-100" + str(group_call.full_chat.id))
327 | chat = await client.get_chat(chat_id)
328 | reply = await m.reply_text(
329 | f"{emoji.MUSICAL_NOTES} **currently in the voice chat**:\n"
330 | f"- **{chat.title}**"
331 | )
332 | else:
333 | reply = await m.reply_text(emoji.NO_ENTRY
334 | + "didn't join any voice chat yet")
335 | await _delay_delete_messages((reply, m), DELETE_DELAY)
336 |
337 |
338 | @Client.on_message(main_filter
339 | & self_or_contact_filter
340 | & current_vc
341 | & filters.regex("^!stop$"))
342 | async def stop_playing(_, m: Message):
343 | group_call = mp.group_call
344 | group_call.stop_playout()
345 | reply = await m.reply_text(f"{emoji.STOP_BUTTON} stopped playing")
346 | await mp.update_start_time(reset=True)
347 | mp.playlist.clear()
348 | await _delay_delete_messages((reply, m), DELETE_DELAY)
349 |
350 |
351 | @Client.on_message(main_filter
352 | & self_or_contact_filter
353 | & current_vc
354 | & filters.regex("^!replay$"))
355 | async def restart_playing(_, m: Message):
356 | group_call = mp.group_call
357 | if not mp.playlist:
358 | return
359 | group_call.restart_playout()
360 | await mp.update_start_time()
361 | reply = await m.reply_text(
362 | f"{emoji.COUNTERCLOCKWISE_ARROWS_BUTTON} "
363 | "playing from the beginning..."
364 | )
365 | await _delay_delete_messages((reply, m), DELETE_DELAY)
366 |
367 |
368 | @Client.on_message(main_filter
369 | & self_or_contact_filter
370 | & current_vc
371 | & filters.regex("^!pause"))
372 | async def pause_playing(_, m: Message):
373 | mp.group_call.pause_playout()
374 | await mp.update_start_time(reset=True)
375 | reply = await m.reply_text(f"{emoji.PLAY_OR_PAUSE_BUTTON} paused",
376 | quote=False)
377 | mp.msg['pause'] = reply
378 | await m.delete()
379 |
380 |
381 | @Client.on_message(main_filter
382 | & self_or_contact_filter
383 | & current_vc
384 | & filters.regex("^!resume"))
385 | async def resume_playing(_, m: Message):
386 | mp.group_call.resume_playout()
387 | reply = await m.reply_text(f"{emoji.PLAY_OR_PAUSE_BUTTON} resumed",
388 | quote=False)
389 | if mp.msg.get('pause') is not None:
390 | await mp.msg['pause'].delete()
391 | await m.delete()
392 | await _delay_delete_messages((reply,), DELETE_DELAY)
393 |
394 |
395 | @Client.on_message(main_filter
396 | & self_or_contact_filter
397 | & current_vc
398 | & filters.regex("^!clean$"))
399 | async def clean_raw_pcm(client, m: Message):
400 | download_dir = os.path.join(client.workdir, DEFAULT_DOWNLOAD_DIR)
401 | all_fn: list[str] = os.listdir(download_dir)
402 | for track in mp.playlist[:2]:
403 | track_fn = f"{track.audio.file_unique_id}.raw"
404 | if track_fn in all_fn:
405 | all_fn.remove(track_fn)
406 | count = 0
407 | if all_fn:
408 | for fn in all_fn:
409 | if fn.endswith(".raw"):
410 | count += 1
411 | os.remove(os.path.join(download_dir, fn))
412 | reply = await m.reply_text(f"{emoji.WASTEBASKET} cleaned {count} files")
413 | await _delay_delete_messages((reply, m), DELETE_DELAY)
414 |
415 |
416 | @Client.on_message(main_filter
417 | & self_or_contact_filter
418 | & current_vc
419 | & filters.regex("^!mute$"))
420 | async def mute(_, m: Message):
421 | group_call = mp.group_call
422 | group_call.set_is_mute(True)
423 | reply = await m.reply_text(f"{emoji.MUTED_SPEAKER} muted")
424 | await _delay_delete_messages((reply, m), DELETE_DELAY)
425 |
426 |
427 | @Client.on_message(main_filter
428 | & self_or_contact_filter
429 | & current_vc
430 | & filters.regex("^!unmute$"))
431 | async def unmute(_, m: Message):
432 | group_call = mp.group_call
433 | group_call.set_is_mute(False)
434 | reply = await m.reply_text(f"{emoji.SPEAKER_MEDIUM_VOLUME} unmuted")
435 | await _delay_delete_messages((reply, m), DELETE_DELAY)
436 |
437 |
438 | @Client.on_message(main_filter
439 | & current_vc
440 | & filters.regex("^(\\/|!)repo$"))
441 | async def show_repository(_, m: Message):
442 | if mp.msg.get('repo') is not None:
443 | await mp.msg['repo'].delete()
444 | mp.msg['repo'] = await m.reply_text(
445 | USERBOT_REPO,
446 | disable_web_page_preview=True,
447 | quote=False
448 | )
449 | await m.delete()
450 |
451 |
452 | # - Other functions
453 |
454 |
455 | async def send_text(text):
456 | group_call = mp.group_call
457 | client = group_call.client
458 | chat_id = mp.chat_id
459 | message = await client.send_message(
460 | chat_id,
461 | text,
462 | disable_web_page_preview=True,
463 | disable_notification=True
464 | )
465 | return message
466 |
467 |
468 | async def skip_current_playing():
469 | group_call = mp.group_call
470 | playlist = mp.playlist
471 | if not playlist:
472 | return
473 | if len(playlist) == 1:
474 | await mp.update_start_time()
475 | return
476 | client = group_call.client
477 | download_dir = os.path.join(client.workdir, DEFAULT_DOWNLOAD_DIR)
478 | group_call.input_filename = os.path.join(
479 | download_dir,
480 | f"{playlist[1].audio.file_unique_id}.raw"
481 | )
482 | await mp.update_start_time()
483 | # remove old track from playlist
484 | old_track = playlist.pop(0)
485 | print(f"- START PLAYING: {playlist[0].audio.title}")
486 | await mp.send_playlist()
487 | os.remove(os.path.join(
488 | download_dir,
489 | f"{old_track.audio.file_unique_id}.raw")
490 | )
491 | if len(playlist) == 1:
492 | return
493 | await download_audio(playlist[1])
494 |
495 |
496 | async def download_audio(m: Message):
497 | group_call = mp.group_call
498 | client = group_call.client
499 | raw_file = os.path.join(client.workdir, DEFAULT_DOWNLOAD_DIR,
500 | f"{m.audio.file_unique_id}.raw")
501 | if not os.path.isfile(raw_file):
502 | original_file = await m.download()
503 | ffmpeg.input(original_file).output(
504 | raw_file,
505 | format='s16le',
506 | acodec='pcm_s16le',
507 | ac=2,
508 | ar='48k',
509 | loglevel='error'
510 | ).overwrite_output().run()
511 | os.remove(original_file)
512 |
513 |
514 | async def _delay_delete_messages(messages: tuple, delay: int):
515 | await asyncio.sleep(delay)
516 | for m in messages:
517 | await m.delete()
518 |
--------------------------------------------------------------------------------
/plugins/vc/radio.py:
--------------------------------------------------------------------------------
1 | """
2 | https://github.com/MarshalX/tgcalls/blob/main/examples/radio_as_smart_plugin.py
3 | 154ef295a3fe3a2383bbd0275a1195c6fafd307d
4 | """
5 | import signal
6 |
7 | # noinspection PyPackageRequirements
8 | import ffmpeg # pip install ffmpeg-python
9 | from pyrogram import Client, filters
10 | from pyrogram.types import Message
11 | from pytgcalls import GroupCall # pip install pytgcalls
12 |
13 | # Example of pinned message in a chat:
14 | '''
15 | Radio stations:
16 |
17 | 1. https://hls-01-regions.emgsound.ru/11_msk/playlist.m3u8
18 |
19 | To start replay to this message with command !start
20 | To stop use !stop command
21 | '''
22 |
23 |
24 | # Commands available only for anonymous admins
25 | async def anon_filter(_, __, m: Message):
26 | return bool(m.from_user is None and m.sender_chat)
27 |
28 |
29 | anonymous = filters.create(anon_filter)
30 |
31 | GROUP_CALLS = {}
32 | FFMPEG_PROCESSES = {}
33 |
34 |
35 | @Client.on_message(anonymous & filters.command('start', prefixes='!'))
36 | async def start(client, message: Message):
37 | input_filename = f'radio-{message.chat.id}.raw'
38 |
39 | group_call = GROUP_CALLS.get(message.chat.id)
40 | if group_call is None:
41 | group_call = GroupCall(client, input_filename, path_to_log_file='')
42 | GROUP_CALLS[message.chat.id] = group_call
43 |
44 | if not message.reply_to_message or len(message.command) < 2:
45 | await message.reply_text(
46 | 'You forgot to replay list of stations or pass a station ID'
47 | )
48 | return
49 |
50 | process = FFMPEG_PROCESSES.get(message.chat.id)
51 | if process:
52 | process.send_signal(signal.SIGTERM)
53 |
54 | station_stream_url = None
55 | station_id = message.command[1]
56 | msg_lines = message.reply_to_message.text.split('\n')
57 | for line in msg_lines:
58 | line_prefix = f'{station_id}. '
59 | if line.startswith(line_prefix):
60 | station_stream_url = (
61 | line.replace(line_prefix, '').replace('\n', '')
62 | )
63 | break
64 |
65 | if not station_stream_url:
66 | await message.reply_text(f'Can\'t find a station with id {station_id}')
67 | return
68 |
69 | await group_call.start(message.chat.id)
70 |
71 | process = ffmpeg.input(station_stream_url).output(
72 | input_filename,
73 | format='s16le',
74 | acodec='pcm_s16le',
75 | ac=2,
76 | ar='48k'
77 | ).overwrite_output().run_async()
78 | FFMPEG_PROCESSES[message.chat.id] = process
79 |
80 | await message.reply_text(f'Radio #{station_id} is playing...')
81 |
82 |
83 | @Client.on_message(anonymous & filters.command('stop', prefixes='!'))
84 | async def stop(_, message: Message):
85 | group_call = GROUP_CALLS.get(message.chat.id)
86 | if group_call:
87 | await group_call.stop()
88 |
89 | process = FFMPEG_PROCESSES.get(message.chat.id)
90 | if process:
91 | process.send_signal(signal.SIGTERM)
92 |
--------------------------------------------------------------------------------
/plugins/vc/recorder.py:
--------------------------------------------------------------------------------
1 | """
2 | tg-vc-userbot, Telegram Voice Chat Userbot
3 | Copyright (C) 2021 Zaute Km
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU Affero General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU Affero General Public License for more details.
14 |
15 | You should have received a copy of the GNU Affero General Public License
16 | along with this program. If not, see .
17 |
18 | Record Audio from Telegram Voice Chat
19 |
20 | Dependencies:
21 | - ffmpeg
22 | - opus-tools
23 | - bpm-tools
24 |
25 | Requirements (pip):
26 | - ffmpeg-python
27 |
28 | Start the userbot and send !record to a voice chat
29 | enabled group chat to start recording for 30 seconds
30 | """
31 | import asyncio
32 | import os
33 | import subprocess
34 | from datetime import datetime
35 |
36 | # noinspection PyPackageRequirements
37 | import ffmpeg
38 | from pyrogram import Client, filters
39 | from pyrogram.types import Message
40 | from pytgcalls import GroupCall, GroupCallAction
41 |
42 | group_call = GroupCall(None, path_to_log_file='')
43 |
44 |
45 | @Client.on_message(filters.group
46 | & filters.text
47 | & filters.outgoing
48 | & ~filters.edited
49 | & filters.regex("^!record$"))
50 | async def record_from_voice_chat(client, m: Message):
51 | group_call.client = client
52 | await group_call.start(m.chat.id)
53 | group_call.add_handler(
54 | network_status_changed_handler,
55 | GroupCallAction.NETWORK_STATUS_CHANGED
56 | )
57 | await m.delete()
58 |
59 |
60 | async def network_status_changed_handler(gc: GroupCall, is_connected: bool):
61 | if is_connected:
62 | print("- JOINED VC")
63 | await record_and_send_opus()
64 | await gc.stop()
65 | else:
66 | print("- LEFT VC")
67 |
68 |
69 | async def record_and_send_opus():
70 | client = group_call.client
71 | chat_id = int("-100" + str(group_call.full_chat.id))
72 | chat = await client.get_chat(chat_id)
73 | status = await client.send_message(chat_id, "1/3 Recording...")
74 | utcnow_unix, utcnow_readable = await get_utcnow()
75 | record_raw, record_opus = f"{utcnow_unix}.raw", f"{utcnow_unix}.opus"
76 | group_call.output_filename = record_raw
77 | await asyncio.sleep(30)
78 | group_call.output_filename = ''
79 | await status.edit_text("2/3 Transcoding...")
80 | ffmpeg.input(
81 | record_raw,
82 | format='s16le',
83 | acodec='pcm_s16le',
84 | ac=2,
85 | ar='48k',
86 | loglevel='error'
87 | ).output(record_opus).overwrite_output().run()
88 | duration = int(float(ffmpeg.probe(record_opus)['format']['duration']))
89 | bpm = subprocess.getoutput(
90 | f"opusdec --quiet --rate 48000 --float {record_opus} - "
91 | "| bpm -f '%0.0f'"
92 | )
93 | probe = ffmpeg.probe(record_opus, pretty=None)
94 | caption = (
95 | f"- BPM: `{bpm}`\n"
96 | f"- Format: `{probe['streams'][0]['codec_name']}`\n"
97 | f"- Channel(s): `{str(probe['streams'][0]['channels'])}`\n"
98 | f"- Sampling rate: `{probe['streams'][0]['sample_rate']}`\n"
99 | f"- Bit rate: `{probe['format']['bit_rate']}`\n"
100 | f"- File size: `{probe['format']['size']}`"
101 | )
102 | performer = (
103 | f"@{chat.username}" if chat.username
104 | else chat.title
105 | )
106 | title = f"[VCREC] {utcnow_readable}"
107 | thumb = await client.download_media(chat.photo.big_file_id)
108 | await status.edit_text("3/3 Uploading...")
109 | await client.send_audio(
110 | chat_id,
111 | record_opus,
112 | caption=caption,
113 | duration=duration,
114 | performer=performer,
115 | title=title,
116 | thumb=thumb)
117 | await status.delete()
118 | for f in (record_raw, record_opus, thumb):
119 | os.remove(f)
120 |
121 |
122 | async def get_utcnow():
123 | utcnow = datetime.utcnow()
124 | utcnow_unix = utcnow.strftime('%s')
125 | utcnow_readable = utcnow.strftime('%Y-%m-%d %H:%M:%S')
126 | return utcnow_unix, utcnow_readable
127 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | TgCrypto
2 | ffmpeg-python
3 | psutil
4 | pytgcalls[pyrogram]
5 | wheel
6 |
--------------------------------------------------------------------------------
/runtime.txt:
--------------------------------------------------------------------------------
1 | python-3.9.5
2 |
--------------------------------------------------------------------------------
/userbot.py:
--------------------------------------------------------------------------------
1 | # import logging
2 | from pyrogram import Client, idle
3 |
4 | app = Client("tgvc")
5 | # logging.basicConfig(level=logging.INFO)
6 | app.start()
7 | print('>>> USERBOT STARTED')
8 | idle()
9 | app.stop()
10 | print('\n>>> USERBOT STOPPED')
11 |
--------------------------------------------------------------------------------