Repository: rongchenlin/BiliBili-Lucky-Draw
Branch: master
Commit: 3d9a0e0ed4a2
Files: 40
Total size: 106.1 KB
Directory structure:
gitextract_ibvvi1vh/
├── .dockerignore
├── .github/
│ └── ISSUE_TEMPLATE/
│ ├── 1.bug.yml
│ └── 2.feature.yml
├── .gitignore
├── Dockerfile
├── LICENSE
├── Other.md
├── Readme.md
├── dao/
│ ├── common_dao.py
│ ├── draw_dynamic_dao.py
│ ├── follow_up_dao.py
│ ├── init_db.py
│ ├── share_info_dao.py
│ ├── shared_url_dao.py
│ └── statistics_dao.py
├── docker-compose.yml
├── lib/
│ └── init_db_script.sql
├── main.py
├── notify.py
├── requirements.txt
├── service/
│ ├── follow_service/
│ │ └── cancel_follow_service.py
│ ├── log_service/
│ │ ├── TextHandler.py
│ │ └── log_printer_service.py
│ ├── login_service/
│ │ ├── check_login_status.py
│ │ └── login_service.py
│ ├── notify_service/
│ │ └── notify_service.py
│ ├── remove_msg.py
│ ├── remove_share.py
│ ├── search_draw_dynamic_service/
│ │ └── SearchDynamicByUps.py
│ ├── share_service/
│ │ ├── cancel_share_service.py
│ │ ├── multi_users_share.py
│ │ ├── share_from_biliLink.py
│ │ └── share_one_dynamic.py
│ └── statistics_service.py
└── utils/
├── file_util.py
├── globals.py
├── ip_util.py
├── mysql_operate.py
├── time_util.py
└── webdriver_util.py
================================================
FILE CONTENTS
================================================
================================================
FILE: .dockerignore
================================================
.git
.gitignore
.dockerignore
.github
.DS_Store
Dockerfile
docker-compose.yml
README.md
Other.md
LICENSE
.vscode
.idea
img/
tests/
.pytest_cache/
.venv//
================================================
FILE: .github/ISSUE_TEMPLATE/1.bug.yml
================================================
name: Bug report 🐛
description: 项目运行中遇到的Bug或问题。
labels: ["status: issue-bug"]
body:
- type: checkboxes
attributes:
label: ⚠️ 搜索issues中是否已存在类似问题
description: >
请在 [历史issue](https://github.com/rongchenlin/BiliBili-Lucky-Draw/issues) 中清空输入框,搜索你的问题
或相关日志的关键词来查找是否存在类似问题。
options:
- label: 我已经搜索过issues和disscussions,没有跟我遇到的问题相关的issue
required: true
- type: dropdown
attributes:
label: 操作系统类型?
description: >
请选择你运行程序的操作系统类型。
options:
- Windows
- Linux
- MacOS
- Docker
- Railway
- Windows Subsystem for Linux (WSL)
- Other (请在问题中说明)
validations:
required: true
- type: dropdown
attributes:
label: 运行的python版本是?
description: |
请选择你运行程序的`python`版本。
options:
- python 3.7
- python 3.8
- python 3.9
- python 3.10
- python 3.11
- other
validations:
required: true
- type: textarea
attributes:
label: 复现步骤 🕹
description: |
**⚠️ 不能复现将会关闭issue.**
- type: textarea
attributes:
label: 问题描述 😯
description: 详细描述出现的问题,或提供有关截图。
- type: textarea
attributes:
label: 终端日志 📒
description: |
在此处粘贴终端日志
value: |
```log
<此处粘贴终端日志>
```
================================================
FILE: .github/ISSUE_TEMPLATE/2.feature.yml
================================================
name: Feature request 🚀
description: 提出你对项目的新想法或建议。
labels: ["status: issue-feature"]
body:
- type: markdown
attributes:
value: |
请在上方的`title`中填写简略总结,谢谢❤️。
- type: checkboxes
attributes:
label: ⚠️ 搜索是否存在类似issue
description: >
请在 [历史issue](https://github.com/rongchenlin/BiliBili-Lucky-Draw/issues) 中清空输入框,搜索关键词查找是否存在相似issue。
options:
- label: 我已经搜索过issues和disscussions,没有发现相似issue
required: true
- type: textarea
attributes:
label: 描述
description: 描述feature的功能。
- type: textarea
attributes:
label: 举例(可选)
description: 提供功能相关的聊天示例,草图或相关网址。
- type: textarea
attributes:
label: 动机
description: 描述你提出该feature的动机,比如没有这项feature对你的使用造成了怎样的影响
================================================
FILE: .gitignore
================================================
pyvenv
.idea
Log
__pycache__
*/__pycache__
/service/*/__pycache__
/*/__pycache__
================================================
FILE: Dockerfile
================================================
FROM python:3
# 复制项目文件到容器中
COPY . /app
# 设置工作目录为项目目录
WORKDIR /app
# 安装项目依赖项
RUN pip install -r requirements.txt -i http://pypi.douban.com/simple --trusted-host pypi.douban.com
# 运行docker run命令
CMD python main.py
================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
================================================
FILE: Other.md
================================================
## <a id="debug_doc">Windows系统调试本程序</a>
### 环境准备

- 创建MySQL,导入lib目录中的SQL脚本`init_db_script.sql`
- 创建Selenium环境
- 点击这个链接:[chromedriver下载地址](http://chromedriver.storage.googleapis.com/index.html) 或者 [下载地址2](https://chromedriver.chromium.org/downloads),下载和当前Chrome匹配的`chromedriver`
- 将下载的`chromedriver.exe`放到lib目录中。
#### 修改代码
到`utils/selenium_util.py`位置,将原本使用docker启动方式的代码注释,本地启动代码。

================================================
FILE: Readme.md
================================================
<div align="center">
<img align="center" src="https://github.com/rongchenlin/BiliBili-Lucky-Draw/blob/master/img/Readme.assets/logo.png" alt="logo" width="600">
<p align="center">· BiliBili-Lucky-Draw ·</p>
<p align="center">
<img src="https://img.shields.io/github/stars/rongchenlin/BiliBili-Lucky-Draw?color=red&style=flat-square">
<a href="mailto:2702739215@qq.com">
<img src="https://img.shields.io/static/v1?label=contact%20me&message=email&color=green&style=flat-square">
</a>
<a href="https://github.com/rongchenlin/BiliBili-Lucky-Draw/blob/master/LICENSE" target="_blank">
<img src="https://img.shields.io/static/v1?label=license&message=GPL-3.0&color=orange&style=flat-square">
</a>
<a href="https://github.com/rongchenlin/BiliBili-Lucky-Draw/issues/new/choose" target="_blank">
<img src="https://img.shields.io/static/v1?label=feedback&message=issues&color=pink&style=flat-square">
</a>
</p>
</br>
</div>
## Ⅰ.简介
常刷B站的伙伴们,是不是每次看到Up主的抽奖活动都心动不已,毕竟`抽奖总得试试吗,万一中奖了呢`,然后一波关注+转发之后,迎来的每每都是`从不缺席,从不中奖`。
So,如果有个小脚本能够帮助你去看看**今天有哪些Up有抽奖活动,然后还能帮助你自动进行抽奖(转发动态+关注)**,那么你是不是可以花更多时间去看看二次元动漫呀。本着有羊毛一起薅的想法,我做了一个B站自动抽奖活动转发的小脚本,帮助伙伴们自动参与Up主的活动转发,提高伙伴们的中奖率,同时还能解放大家的双手,开开心心薅羊毛。
**声明**: <u>**此脚本仅用于学习和测试,作者本人并不对其负责,请于运行测试完成后自行删除,请勿滥用!**</u>
## Ⅱ.效果
本程序内置一个扫描脚本,该脚本去挖掘那些经常转发抽奖动态的伙伴,然后每天定时去扫描他们今天的动态信息,随后再利用一个抽奖动态识别与转发脚本来进行活动参与,转发后的效果是这样的:

## III.使用:Docker部署(推荐)
### 1.Clone本项目
### 2.获取B站Cookie
> 苹果Mac电脑参考:[点击这里](https://github.com/BilibiliVideoDownload/BilibiliVideoDownload/wiki/%E8%8E%B7%E5%8F%96SESSDATA)
> window电脑详细方法参考:[点击这里](https://zhuanlan.zhihu.com/p/383171889)
在浏览器进入[B站](https://www.bilibili.com/),然后登录,随后按照下图获取cookie值
在`.env`文件中,修改相关信息:

### 3.设置Cookie和本机IP
注意:本机IP建议不要填127.0.0.1,而是填写实际IP。
在本项目的.env文件中,将第2步获取的cookie值填入下图位置

### 4.在Docker中分别执行下面两条命令
编译命令:
```dockerfile
docker-compose build
```
运行容器:
```
docker-compose up -d
```
<u>Tip:如果要停止容器,可以使用命令:`docker-compose down`</u>
### 5.确认是否运行成功
等待docker运行成功后,点击进入 your_ip:5555/ui/sessions,然后点击正在执行的项目,看是否出现如下截图
## IV.TODO && Updated
- [x] 项目采用Docker部署
- [x] 扫描B站二维码登录B站,自动生成Cookie并保存到本地项目文件夹cookie中
- [x] 登录过期,使用Cookie续期
- [x] 每日任务执行情况推送(之前用的方糖酱,后续将重新加入)
- [x] 将数据库搭建的工作使用Docker部署
- [x] Docker服务编排,一键部署
- [x] 开发桌面程序(目前只是简单版本)
- [x] 过期动态的删除
- [x] 接入B站UP主每日总结的抽奖动态列表,自动完成对其转发
---
## Ⅶ.Thanks
**本程序仅用于学习**
**有问题欢迎大家提Issue,有时间我会帮忙解决,也请大佬有好的解决方案在Issue上分享,更加欢迎大家提出PR,成为项目的贡献者。**
如果大家觉得这个项目有点意思,期待给个Star :star:,你的Star :star:是作者更新最大的动力鸭!
<picture>
<source
media="(prefers-color-scheme: dark)"
srcset="
https://api.star-history.com/svg?repos=rongchenlin/BiliBili-Lucky-Draw&type=Date&theme=dark
"
/>
<source
media="(prefers-color-scheme: light)"
srcset="
https://api.star-history.com/svg?repos=rongchenlin/BiliBili-Lucky-Draw&type=Date
"
/>
<img
alt="Star History Chart"
src="https://api.star-history.com/svg?repos=rongchenlin/BiliBili-Lucky-Draw&type=Date"
/>
</picture>
================================================
FILE: dao/common_dao.py
================================================
from dao.init_db import init_db
class CommonDao(object):
def __init__(self, db):
self.db = db
def common_query(self, table_name="", cond_dict="", order="", fields="*"):
try:
"""
调用方法:
data = common_query(table_name="t_share_info")
data = common_query(table_name="t_share_info", order='order by id')
data = common_query(table_name="t_share_info", cond_dict={'status': '0'}, order='order by id', fields=["id", "share_url"])
"""
return self.db.select(table_name, cond_dict, order, fields)
except Exception as e:
return {}
def common_insertMany(self, table, attrs, values):
"""
调用方法:
data = common_query(table_name="t_share_info")
data = common_query(table_name="t_share_info", order='order by id')
data = common_query(table_name="t_share_info", cond_dict={'status': '0'}, order='order by id', fields=["id", "share_url"])
"""
try:
self.db.insertMany(table, attrs, values)
return 0
except Exception as e:
return 1
================================================
FILE: dao/draw_dynamic_dao.py
================================================
from datetime import datetime
class DrawDynamicDao(object):
def __init__(self, db):
self.table_name = 't_draw_dynamic'
self.db = db
def query_by_time(self, time, limit=2000, status=1):
try:
sql = ("SELECT * FROM " + self.table_name
+ " where status = '" + str(status)
+ "' and insert_time >= '" + time
+ "' limit " + str(limit))
data = self.db.select_db(sql) # 用mysql_operate文件中的db的select_db方法进行查询
return data
except Exception as e:
return {}
def query_by_dyn_url(self, dyn_url):
try:
sql = "SELECT * FROM " + self.table_name + " where dyn_url = '" + dyn_url + "'";
data = self.db.select_db(sql) # 用mysql_operate文件中的db的select_db方法进行查询
return data
except Exception as e:
return {}
def insert(self, dyn_url, source, note):
try:
params = {}
params['dyn_url'] = str(dyn_url)
params['source'] = str(source)
params['status'] = '0'
params['note'] = str(note)
params['insert_time'] = str(datetime.now())
self.db.insert(self.table_name, params)
return True
except Exception as e:
return False
def update_sharedUrl(self, url, status):
try:
params = {'status': str(status)}
cond_dict = {'dyn_url': url}
self.db.update(self.table_name, params, cond_dict)
except Exception as e:
print(e)
================================================
FILE: dao/follow_up_dao.py
================================================
from datetime import datetime
class FollowUpInfoDao(object):
def __init__(self,db):
self.db = None
self.table_name = 't_followdups'
self.db = db
def query_followUpInfo_by_UpId(self, up_id, user_id):
try:
sql = "SELECT * FROM " + self.table_name + " where up_id = '" + up_id + "'" + " and user_id = '" + user_id + "'";
data = self.db.select_db(sql) # 用mysql_operate文件中的db的select_db方法进行查询
return data
except Exception as e:
return {}
def saverUpdate(self, up_id, up_url, user_id):
try:
params = {}
params['up_id'] = str(up_id)
params['user_id'] = str(user_id)
params['up_url'] = str(up_url)
params['update_time'] = str(datetime.now())
data = self.query_followUpInfo_by_UpId(up_id, user_id)
if len(data) == 0:
params['status'] = str(1)
self.db.insert(self.table_name, params)
else:
status = int(data[0]['status'])
status = status + 1
params['status'] = str(status)
cond_dict = {'up_id': up_id,'user_id': user_id}
self.db.update(self.table_name, params, cond_dict)
except Exception as e:
print(e)
================================================
FILE: dao/init_db.py
================================================
import logging
import pymysql
from utils.mysql_operate import MysqldbHelper
from utils.globals import db_host, port, user, passwd, charset, dbname
def init_db():
"""
初始化数据库连接
:return:
"""
config = {
'host': db_host,
'port': port,
'user': user,
'passwd': passwd,
'charset': charset,
'cursorclass': pymysql.cursors.DictCursor
}
logging.warning("ip :" + str(db_host))
logging.info("db info :")
logging.info(config)
db = MysqldbHelper(config)
db.selectDataBase(dbname)
logging.warning("创建数据库连接信息 :" + str(config))
return db
================================================
FILE: dao/share_info_dao.py
================================================
from dao.init_db import init_db
from service.share_service.share_one_dynamic import DynamicShareBase
class ShareInfoDao(object):
def __init__(self, db):
self.table_name = 't_share_info'
self.db = db
def query_shareInfo_by_userIdAndTime(self, user_id, share_time):
"""
根据转发的url查询
:param user_id:
:param share_url:
:return:
"""
try:
sql = "SELECT * FROM " + self.table_name + " where user_id = '" + user_id + "'" + " and share_time >= '" + share_time + "'";
data = self.db.select_db(sql)
return data
except Exception as e:
return {}
def query_shareInfo_by_shareUrl(self, share_url, user_id):
"""
根据转发的url查询
:param user_id:
:param share_url:
:return:
"""
try:
sql = "SELECT * FROM " + self.table_name + " where share_url = '" + share_url + "'" + " and user_id = '" + user_id + "'";
data = self.db.select_db(sql)
return data
except Exception as e:
return {}
def insert_shareInfo(self, shareInfo):
try:
params = {}
params['upId'] = str(shareInfo.upId)
params['upUrl'] = str(shareInfo.upUrl)
params['share_url'] = str(shareInfo.share_url)
params['status'] = str(shareInfo.status)
params['machine_ip'] = str(shareInfo.machine_ip)
params['share_time'] = str(shareInfo.share_time)
params['user_id'] = str(shareInfo.user_id)
params['share_status'] = str(shareInfo.share_status)
self.db.insert(self.table_name, params)
except Exception as e:
print(e)
if __name__ == '__main__':
db = init_db()
shareInfodao = ShareInfoDao(db)
# dyn = DynamicShareBase()
# dyn.upUrl = '1'
# dyn.upId = '2'
# dyn.share_url = '2share_url'
# dyn.status = 1
# dyn.machine_ip = '2machine_ip'
# dyn.share_time = '2022-12-12'
# dyn.share_status = 1
================================================
FILE: dao/shared_url_dao.py
================================================
from datetime import datetime
from dao.init_db import init_db
from service.share_service.share_one_dynamic import DynamicShareBase
class SharedUrlDao(object):
def __init__(self, db):
self.table_name = 't_shared_urls'
self.db = db
def query_sharedUrls_limit(self, user_id, status, limit):
"""
根据转发的url查询
:param user_id:
:param share_url:
:return:
"""
try:
sql = ("SELECT * FROM " + self.table_name
+ " where user_id = '" + user_id + "'" + " and status = '" + status + "'"
+ " ORDER BY dyn_url"
+ " limit " + str(limit) + ";");
data = self.db.select_db(sql)
return data
except Exception as e:
print(e)
return {}
def insert_sharedUrl(self, user_id, url):
try:
params = {'dyn_url': str(url), 'user_id': user_id, 'insert_time': str(datetime.now()), 'status': '0'}
self.db.insert(self.table_name, params)
except Exception as e:
print(e)
def update_sharedUrl(self, user_id, url, status):
try:
params = {'update_time': str(datetime.now()), 'status': str(status)}
cond_dict = {'dyn_url': url, 'user_id': user_id}
self.db.update(self.table_name, params, cond_dict)
except Exception as e:
print(e)
================================================
FILE: dao/statistics_dao.py
================================================
from datetime import datetime, timedelta
from dao.init_db import init_db
class StatisticsDao(object):
def __init__(self, db):
self.table_name = 't_statistics'
self.db = db
def query_by_time(self, time):
try:
sql = "SELECT * FROM " + self.table_name + " where insert_time >= '" + time + "'";
data = self.db.select_db(sql) # 用mysql_operate文件中的db的select_db方法进行查询
return data
except Exception as e:
return {}
def query_today_data(self):
# 获取今天的日期
today = datetime.now()
# 计算昨天的日期
yesterday = today - timedelta(days=1)
# 将日期格式化为字符串
yesterday_str = yesterday.strftime("%Y-%m-%d")
today_str = today.strftime("%Y-%m-%d")
text = ""
datas = self.query_by_time(today_str)
for data in datas:
text = text + str(data['insert_time']) + "\n内容:[" + data['user_id'] + data['content'] + "]\n备注:[" + data['note'] + "]\n\n"
return text
def insert(self, user_id, content, note):
try:
params = {'user_id': str(user_id), 'content': str(content), 'note': str(note),
'insert_time': str(datetime.now())}
self.db.insert(self.table_name, params)
return True
except:
return False
================================================
FILE: docker-compose.yml
================================================
version: '3'
services:
bili-db:
image: mysql:5.7
container_name: bili-db
environment:
MYSQL_ROOT_PASSWORD: luckybililuckybili
MYSQL_DATABASE: luckybili
MYSQL_USER: luckybili
MYSQL_PASSWORD: luckybililuckybili
ports:
- "3206:3306"
volumes:
- ./lib/init_db_script.sql:/docker-entrypoint-initdb.d/init_db_script.sql # 挂载init_db_script.sql文件到容器内的初始化目录
- ./db_data:/var/lib/mysql # 持久化MySQL数据
command: --default-authentication-plugin=mysql_native_password
bili-selenium:
image: selenium/standalone-chrome:latest
container_name: bili-selenium
ports:
- 5555:4444
- 7900:7900
shm_size: 1g
environment:
- SE_NODE_MAX_SESSIONS=5
- SE_NODE_MAX_INSTANCES=5
- SE_NODE_OVERRIDE_MAX_SESSIONS=true
# 执行转发动态的服务
dynamic_share:
build:
context: .
dockerfile: Dockerfile
volumes:
- .:/app
restart: always
depends_on:
- bili-selenium
- bili-db
================================================
FILE: lib/init_db_script.sql
================================================
-- create database luckybili default character set utf8mb4 collate utf8mb4_general_ci;
use luckybili;
create table t_draw_dynamic
(
dyn_url varchar(255) charset latin1 not null
primary key,
insert_time datetime null,
source varchar(255) charset latin1 null,
note varchar(255) null,
status varchar(20) null
)
collate = utf8_bin;
create table t_followdups
(
id int auto_increment
primary key,
up_id varchar(255) null,
up_url varchar(255) null,
status int null,
update_time datetime null,
user_id varchar(50) null
)
comment '关注的up主信息';
create table t_prize
(
id int auto_increment
primary key,
status int null,
prize_url varchar(255) null,
user_id varchar(50) null
)
comment '中奖信息表';
create table t_share_info
(
id int auto_increment,
share_url varchar(255) null,
status int not null comment '当前动态状态',
upId varchar(50) null,
upUrl varchar(255) null,
machine_ip varchar(20) null,
share_time datetime null,
share_status int null,
user_id varchar(50) null,
constraint t_share_info_pk
unique (id)
)
comment '动态转发的基本信息表';
create table t_shared_urls
(
dyn_url varchar(255) not null,
insert_time datetime null,
update_time datetime null,
status varchar(50) null,
user_id varchar(20) not null,
primary key (user_id, dyn_url)
);
create table t_statistics
(
id int auto_increment
primary key,
content varchar(255) collate utf8_bin null,
insert_time datetime null,
note varchar(500) collate utf8_bin null comment '备注',
user_id varchar(50) null
);
================================================
FILE: main.py
================================================
import time
import schedule
from service.search_draw_dynamic_service.SearchDynamicByUps import SearchDynamicByUps
from service.share_service.multi_users_share import MultiUsersShareService
from utils import globals
def do_search():
SearchDynamicByUps(globals.my_user_id).init_search()
def do_share():
MultiUsersShareService().do_multi_uses_share()
if __name__ == '__main__':
time.sleep(15)
do_search()
do_share()
schedule.every().day.at("15:42").do(do_search)
schedule.every().day.at("15:45").do(do_share)
while True:
try:
schedule.run_pending()
time.sleep(1)
except Exception as e:
time.sleep(1)
================================================
FILE: notify.py
================================================
from service.notify_service.notify_service import NotifyService
from service.remove_share import RemoveShareService
from service.statistics_service import StatisticsService
from utils import globals
if __name__ == '__main__':
cnt, content = StatisticsService().today_data()
NotifyService().fangtang_msg_push_by_content(title="每日统计", content=content)
print('每日统计结果: ' + content)
RemoveShareService(globals.my_user_id, cnt=globals.remove_cnt).start_remove_service()
================================================
FILE: service/follow_service/cancel_follow_service.py
================================================
class CancelFollowService(object):
def __init__(self):
print()
================================================
FILE: service/log_service/TextHandler.py
================================================
import logging
import tkinter as tk
class TextHandler(logging.Handler):
def __init__(self, text_widget):
super().__init__()
self.text_widget = text_widget
def emit(self, record):
log_msg = self.format(record) + "\n"
self.text_widget.config(state=tk.NORMAL)
self.text_widget.insert(tk.END, log_msg)
self.text_widget.see(tk.END)
self.text_widget.config(state=tk.DISABLED)
================================================
FILE: service/log_service/log_printer_service.py
================================================
import logging
import time
import os
class MyLogger(object):
def __init__(self, name=None):
self.name = name
# ①创建一个记录器
self.logger = logging.getLogger(self.name)
self.logger.setLevel("INFO") # 设置日志级别为 'level',即只有日志级别大于等于'level'的日志才会输出
self.formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") # 创建formatter
# ②创建屏幕-输出到控制台,设置输出等级
self.streamHandler = logging.StreamHandler()
self.streamHandler.setLevel("INFO")
# ③创建log文件,设置输出等级
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 根目录
time_now = time.strftime('%Y_%m_%d_%H', time.localtime()) + '_err' + '.log' # log文件命名:2022_04_02_21.log
self.fileHandler = logging.FileHandler(os.path.join('./', "Log", time_now ), 'a', encoding='utf-8')
self.fileHandler.setLevel("ERROR")
# ④用formatter渲染这两个Handler
self.streamHandler.setFormatter(self.formatter)
self.fileHandler.setFormatter(self.formatter)
# ⑤将这两个Handler加入logger内
self.logger.addHandler(self.streamHandler)
self.logger.addHandler(self.fileHandler)
def getLogger(self):
return self.logger
def print_run_time(self, name, begin_time, end_time):
"""
计算运行时间
:param name:
:param begin_time:
:param end_time:
:return:
"""
run_time = round(end_time - begin_time)
# 计算时分秒
hour = run_time // 3600
minute = (run_time - 3600 * hour) // 60
second = run_time - 3600 * hour - 60 * minute
run_time_show = f'\r\n\r\n{name} 总共运行时间:{hour}小时{minute}分钟{second}秒'
return run_time_show
================================================
FILE: service/login_service/check_login_status.py
================================================
import logging
import os
from utils.file_util import get_value_from_env
logging.basicConfig(level=logging.INFO)
def check_cookie_status():
try:
file_name = ''
if os.path.exists(os.path.join('./', '.env')):
# 加载 .env 文件
my_user_id_value = get_value_from_env(".env", "my_user_id")
file_name = my_user_id_value + '.txt'
if os.path.exists(os.path.join('./cookie', file_name)):
return True
else:
return False
except Exception as e:
return False
================================================
FILE: service/login_service/login_service.py
================================================
import json
from time import sleep
from urllib.parse import urlparse
from selenium.webdriver.common.by import By
from service.log_service.log_printer_service import MyLogger
from utils import globals
from utils.file_util import append_data_to_env
from utils.time_util import random_sleep
from utils.webdriver_util import ElementUtil, init_webdriver
mylogger = MyLogger('login_service.py').getLogger()
class LoginService(object):
def __init__(self, bro, chains, my_user_id='0'):
self.bro = bro
self.chains = chains
self.my_user_id = my_user_id
mylogger.info('启动登录模块')
def login_manual(self):
self.bro.get(globals.home_url)
while ElementUtil.is_xpath_exist(self.bro, self.chains,
'//*[@id="i_cecream"]/div[2]/div[1]/div[1]/ul[2]/li[1]/li/div') is True:
random_sleep()
dict_cookies = self.bro.get_cookies()
json_cookies = json.dumps(dict_cookies)
try:
url = self.bro.find_element(By.XPATH,
'//*[@id="i_cecream"]/div[2]/div[1]/div[1]/ul[2]/li[1]/div[1]/a[1]').get_attribute(
"href")
except Exception as e:
print(e)
result = urlparse(url)
id = str(result[2])[1:]
cookie_path = './cookie/' + id + '.txt'
with open(cookie_path, 'w') as f:
f.write(json_cookies)
def login_by_cookie(self):
"""
根据保存的Cookie信息进行登录
:param bro:
:return:
"""
try:
self.bro.get(globals.home_url)
cookie_value = globals.cookie_value
cookie = {"domain": ".bilibili.com", "expiry": 1717635533, "name": "SESSDATA", "path": "/", "sameSite": "Lax", "value": cookie_value}
self.bro.add_cookie(cookie)
self.bro.refresh()
mylogger.info('使用cookie自动登录成功!')
random_sleep(start=1, end=2)
except Exception as e:
mylogger.error('登录失败')
mylogger.error("[出错原因为:%s]" % e)
def login_by_cookie2(self):
"""
根据保存的Cookie信息进行登录
:param bro:
:return:
"""
try:
cookie_path = './cookie/' + self.my_user_id + '.txt'
self.bro.get(globals.home_url)
with open(cookie_path, 'r', encoding='utf-8') as f:
cookies = f.readlines()
for cookie in cookies:
cookie = cookie.replace(r'\n', '')
cookie_li = json.loads(cookie)
random_sleep(start=1, end=2)
for cookie in cookie_li:
self.bro.add_cookie(cookie)
self.bro.refresh()
mylogger.info('使用cookie自动登录成功!')
random_sleep(start=1, end=2)
except Exception as e:
mylogger.error('登录失败')
mylogger.error("[出错原因为:%s]" % e)
================================================
FILE: service/notify_service/notify_service.py
================================================
import requests
from dao.init_db import init_db
from dao.statistics_dao import StatisticsDao
from utils import globals
class NotifyService(object):
def __init__(self):
self.key = globals.FangTang_KEY
self.statistics_dao = StatisticsDao(init_db())
def fangtang_msg_push(self):
"""
方糖
https://zhuanlan.zhihu.com/p/377659574
https://sct.ftqq.com/sendkey
:return:
"""
try:
self.text = self.statistics_dao.query_today_data()
url = 'https://sc.ftqq.com/%s.send' % self.key
requests.post(url, data={'text': "程序通知", 'desp': self.text})
except Exception as e:
print()
def fangtang_msg_push_by_content(self, title="", content=""):
"""
方糖
https://zhuanlan.zhihu.com/p/377659574
https://sct.ftqq.com/sendkey
:param key:
:return:
"""
try:
url = 'https://sc.ftqq.com/%s.send' % self.key
if globals.notify_switch == 'Y':
requests.post(url, data={'text': title, 'desp': content})
except Exception as e:
print()
if __name__ == '__main__':
# NotifyService().fangtang_msg_push(key="b0e892e8856d5a45a415c739489b13b9")
print()
================================================
FILE: service/remove_msg.py
================================================
import time
from selenium.webdriver import ActionChains, Keys
from service.log_service.log_printer_service import MyLogger
from service.login_service.login_service import LoginService
from utils.time_util import random_sleep
from utils.webdriver_util import init_webdriver, ElementUtil
from utils import globals
mylogger = MyLogger('remove_msg.py').getLogger()
class RemoveMsgService(object):
"""
多用户转发模式
"""
def __init__(self, user_id, cnt, bro, chains):
self.user_id = user_id
self.cnt = cnt
self.bro = bro
self.chains = chains
mylogger.error('移除通知信息!')
def do_remove(self):
base_url = 'https://message.bilibili.com/?spm_id_from=333.1007.0.0#/whisper'
try:
# bro, chains = init_webdriver()
# LoginService(self.bro, self.chains, self.user_id).login_by_cookie()
self.bro.get(base_url)
first_dyn_element = ElementUtil.get_element_by_xpath(self.bro, self.chains,'//*[@id="link-message-container"]/div[1]/div[2]/div[2]/div[1]/div/div/div[4]/div[2]/div[1]/div[1]')
# 创建ActionChains对象
actions = ActionChains(self.bro)
actions.move_to_element(first_dyn_element).perform()
# 循环滚动和点击
scroll_distance = 2
for i in range(self.cnt): # 你可以根据需要设置循环次数
# 模拟滚轮滚动
ActionChains(self.bro).send_keys(Keys.ARROW_DOWN * scroll_distance).perform()
# 等待一段时间,确保页面有足够的时间进行滚动
time.sleep(1)
ActionChains(self.bro).click().perform()
random_sleep(start=1, end=5)
except:
mylogger.error("[移除通知信息流程 出错]")
finally:
print(1)
if __name__ == '__main__':
RemoveMsgService(globals.my_user_id).do_remove()
================================================
FILE: service/remove_share.py
================================================
import time
from selenium.webdriver import ActionChains, Keys
from dao.init_db import init_db
from dao.shared_url_dao import SharedUrlDao
from service.log_service.log_printer_service import MyLogger
from service.login_service.login_service import LoginService
from utils.time_util import random_sleep
from utils.webdriver_util import init_webdriver, ElementUtil
from utils import globals
mylogger = MyLogger('remove_share.py').getLogger()
class RemoveShareService(object):
"""
多用户转发模式
"""
def __init__(self, user_id, cnt=None, bro=None, chains=None):
self.user_id = user_id
self.db = init_db()
self.sharedUrlDao = SharedUrlDao(self.db)
if bro is None:
self.bro, self.chains = init_webdriver()
LoginService(self.bro, self.chains, self.user_id).login_by_cookie()
else:
self.bro = bro
self.chains = chains
self.cnt = cnt
mylogger.error('移除通知信息!')
def get_expired_url(self, scroll_cnt):
base_url = 'https://space.bilibili.com/385649497/dynamic'
try:
self.bro.get(base_url)
scroll_path = '//*[@id="page-dynamic"]'
first_dyn_element = ElementUtil.get_element_by_xpath(self.bro, self.chains, scroll_path)
# 创建ActionChains对象
actions = ActionChains(self.bro)
actions.move_to_element(first_dyn_element).perform()
# 循环滚动和点击
scroll_distance = 400
for i in range(scroll_cnt): # 你可以根据需要设置循环次数
# 模拟滚轮滚动
ActionChains(self.bro).send_keys(Keys.ARROW_DOWN * scroll_distance).perform()
random_sleep(start=1, end=4)
div_elements = self.bro.find_elements_by_xpath("//div[@class='bili-dyn-more__menu__item']")
# 遍历每个<div>元素,检查是否包含data-params属性,并提取dynamic_id的值
for div_element in div_elements:
class_attribute = div_element.get_attribute("class")
data_params_attribute = div_element.get_attribute("data-params")
# 检查是否包含class="bili-dyn-more__menu__item"以及data-params属性
if "bili-dyn-more__menu__item" in class_attribute and data_params_attribute:
# 提取dynamic_id的值
dynamic_id_start = data_params_attribute.find('"dynamic_id"') + len('"dynamic_id"') + 1
dynamic_id_end = data_params_attribute.find('"', dynamic_id_start + 1)
dynamic_id_value = data_params_attribute[dynamic_id_start + 1:dynamic_id_end].strip()
if dynamic_id_value != '':
url = 'https://www.bilibili.com/opus/' + dynamic_id_value
self.sharedUrlDao.insert_sharedUrl(self.user_id, url)
except Exception as e:
mylogger.error("[获取过期动态流程 出错 %s]" % e, exc_info=True)
def do_remove(self):
"""
批量删除过期url
:return:
"""
try:
datas = self.sharedUrlDao.query_sharedUrls_limit(self.user_id, '0', self.cnt)
for data in datas:
lucky_dynamic_url = data['dyn_url']
self.remove_one(lucky_dynamic_url)
except:
mylogger.error("[do_remove 批量删除过期url 出错]")
def remove_one(self, lucky_dynamic_url):
"""
移除一个过期url
:param lucky_dynamic_url: 需要进行转发的抽奖动态的URL
:return:
"""
try:
self.bro.get(lucky_dynamic_url)
self.bro.refresh()
ElementUtil.wait_to_go(self.bro)
self.click_delete(self.bro, self.chains)
random_sleep()
# 回填状态
self.sharedUrlDao.update_sharedUrl(self.user_id, lucky_dynamic_url, '1')
except Exception as e:
mylogger.error("remove_one 移除一个过期url 出错url : " + lucky_dynamic_url)
finally:
mylogger.info('移除一个过期url--执行结束')
def click_delete(self, bro, chains):
"""
点赞
:param bro:
:param chains:
:return:
"""
try:
find_path = '//*[@id="app"]/div[3]/div/div/div[1]/div[2]/div[4]/div'
find_path_ele = ElementUtil.get_element_by_xpath(bro, chains, find_path)
chains.click(find_path_ele).perform()
random_sleep(start=1, end=3)
delete_path = '//*[@id="app"]/div[3]/div/div/div[1]/div[2]/div[4]/div/div'
delete_path_ele = ElementUtil.get_element_by_xpath(bro, chains, delete_path)
chains.click(delete_path_ele).perform()
random_sleep(start=1, end=3)
do_delete_path = '/html/body/div[4]/div[2]/div[4]/button[2]'
do_delete_ele = ElementUtil.get_element_by_xpath(bro, chains, do_delete_path)
chains.click(do_delete_ele).perform()
random_sleep(start=1, end=3)
except Exception as e:
mylogger.error("[click_like 点击“删除” 出错 %s]" % e, exc_info=True)
raise
def quilt_bro(self):
self.bro.quit()
def start_remove_service(self):
if globals.is_remove == 'Y':
self.do_remove()
self.get_expired_url(10)
self.quilt_bro()
else:
mylogger.error("移除过期url开关未打开")
================================================
FILE: service/search_draw_dynamic_service/SearchDynamicByUps.py
================================================
import time
from datetime import datetime
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from dao.draw_dynamic_dao import DrawDynamicDao
from dao.init_db import init_db
from dao.statistics_dao import StatisticsDao
from service.log_service.log_printer_service import MyLogger
from service.login_service.login_service import LoginService
from service.notify_service.notify_service import NotifyService
from utils.ip_util import remove_query_string
from utils.time_util import random_sleep
from utils.webdriver_util import init_webdriver, ElementUtil
from utils import globals
mylogger = MyLogger('SearchDynamicByUps.py').getLogger()
class SearchDynamicByUps(object):
def __init__(self, user_id):
self.count = 0
self.user_id = user_id
self.search_note = ""
db = init_db()
self.draw_dynamic_dao = DrawDynamicDao(db)
self.statistics_dao = StatisticsDao(db)
def searchFromFiftyUps(self, bro, chains):
"""
up主:你的工具人老公
up主链接:https://space.bilibili.com/100680137/dynamic
来源:https://space.bilibili.com/100680137/dynamic
:return:
"""
base_url = 'https://space.bilibili.com/100680137/dynamic'
try:
# 前往主页
bro.get(base_url)
bro.refresh()
pathOne = '//*[@id="page-dynamic"]/div[1]/div/div[1]/div[1]/div/div[2]/div[3]/div/div/div/div/div[2]'
first_dyn_element = ElementUtil.get_element_by_xpath(bro, chains, pathOne)
first_dyn_element.click()
ElementUtil.wait_to_go(bro)
bro.switch_to.window(bro.window_handles[-1])
bro.refresh()
random_sleep()
# 到达动态列表页
source_url = bro.current_url
# 获取链接所在的块
all_links_ele = ElementUtil.get_element_by_xpath(bro, chains, '/html/body/div[3]/div/div[3]/div[1]/div[4]/div')
# 在<div>元素下找到所有<a>标签元素
link_elements = all_links_ele.find_elements_by_xpath(".//a")
links = [element.get_attribute("href") for element in link_elements]
self.dynLinks_to_db(links, remove_query_string(source_url), "你的工具人老公")
except Exception as e:
mylogger.error("[searchFromFiftyUps 从“你的工具人老公”查找抽奖动态 出错 %s]" % e, exc_info=True)
NotifyService().fangtang_msg_push_by_content(title="“你的工具人老公”查找抽奖动态出错", content='从“你的工具人老公”查找抽奖动态 出错')
def searchFromBigFish(self, bro, chains):
"""
up主:_大锦鲤_
up主链接:https://space.bilibili.com/226257459/dynamic
:return:
"""
base_url = 'https://space.bilibili.com/226257459/dynamic'
try:
bro.get(base_url)
bro.refresh()
pathOne = '//*[@id="page-dynamic"]/div[1]/div/div[1]/div[1]/div/div/div[3]/div/div/div/div'
base_link_element = ElementUtil.get_element_by_xpath(bro, chains, pathOne)
base_link_element.click()
WebDriverWait(bro, 10).until(EC.new_window_is_opened)
bro.switch_to.window(bro.window_handles[-1])
bro.refresh()
random_sleep()
# 到达动态列表页
source_url = bro.current_url
# 获取这些<a>标签的href属性值
elements = ElementUtil.get_elementArr_by_xpath(bro, chains, '//a[contains(text(), "网页链接")]')
links = [element.get_attribute("href") for element in elements]
filtered_links = [link for link in links if "mall.bilibili" not in link]
self.dynLinks_to_db(filtered_links, remove_query_string(source_url), "_大锦鲤_")
except Exception as e:
mylogger.error("[searchFromBigFish 从“_大锦鲤_”查找抽奖动态 出错 %s]" % e, exc_info=True)
NotifyService().fangtang_msg_push_by_content(title="“_大锦鲤_”查找抽奖动态出错", content='从“_大锦鲤_”查找抽奖动态 出错')
def searchFromCarcinus_(self, bro, chains):
"""
up主:Carcinus_
up主链接:https://space.bilibili.com/27332255/dynamic
:return:
"""
base_url = 'https://space.bilibili.com/27332255/dynamic'
try:
bro.get(base_url)
bro.refresh()
pathOne = '//*[@id="page-dynamic"]/div[1]/div/div[1]/div[1]/div/div/div[3]/div/div/div/div/div[1]'
base_link_element = ElementUtil.get_element_by_xpath(bro, chains, pathOne)
base_link_element.click()
WebDriverWait(bro, 10).until(EC.new_window_is_opened)
bro.switch_to.window(bro.window_handles[-1])
bro.refresh()
random_sleep()
# 到达动态列表页
source_url = bro.current_url
# 获取这些<a>标签的href属性值
elements = ElementUtil.get_elementArr_by_xpath(bro, chains, '//a[contains(text(), "LINK")]')
links = [element.get_attribute("href") for element in elements]
self.dynLinks_to_db(links, remove_query_string(source_url), "Carcinus_")
except Exception as e:
mylogger.error("[searchFromCarcinus_ 从“Carcinus_”查找抽奖动态 出错 %s]" % e, exc_info=True)
NotifyService().fangtang_msg_push_by_content(title="“Carcinus_”查找抽奖动态出错", content='从“Carcinus_”查找抽奖动态 出错')
def searchFromSmile(self, bro, chains):
"""
up主:闻不着味
up主链接:https://space.bilibili.com/280025263/dynamic
:return:
"""
base_url = 'https://space.bilibili.com/280025263/dynamic'
try:
bro.get(base_url)
bro.refresh()
pathOne = self.find_first_ele(bro, chains)
base_link_element = ElementUtil.get_element_by_xpath(bro, chains, pathOne)
base_link_element.click()
WebDriverWait(bro, 10).until(EC.new_window_is_opened)
bro.switch_to.window(bro.window_handles[-1])
bro.refresh()
random_sleep()
# 到达动态列表页
source_url = bro.current_url
# 获取这些<a>标签的href属性值
elements = ElementUtil.get_elementArr_by_xpath(bro, chains, '//a[contains(text(), "http")]')
links = [element.get_attribute("href") for element in elements]
self.dynLinks_to_db(links, remove_query_string(source_url), "闻不着味")
except Exception as e:
mylogger.error("[searchFromSmile 从“闻不着味”查找抽奖动态 出错 %s]" % e, exc_info=True)
NotifyService().fangtang_msg_push_by_content(title="“闻不着味”查找抽奖动态出错", content='从“闻不着味”查找抽奖动态 出错')
def find_first_ele(self, bro, chains):
pathOnes = [
'//*[@id="page-dynamic"]/div[1]/div/div[1]/div[1]/div/div[2]/div[3]/div/div/div/div/div[1]'
'//*[@id="page-dynamic"]/div[1]/div/div[1]/div[1]/div/div[2]/div[3]/div/div/div/div',
'//*[@id="page-dynamic"]/div[1]/div/div[1]/div[1]/div/div[2]/div[3]/div/div/div/div/div[2]',
'//*[@id="page-dynamic"]/div[1]/div/div[1]/div[1]/div/div[2]/div[3]/div/div[3]/div[2]/div/div[1]',
]
for pathOne in pathOnes:
if ElementUtil.is_xpath_exist(bro, chains,pathOne):
return pathOne
return None;
def dynLinks_to_db(self, dynLinks, source, note):
cnt = 0
break_flag = 0
ignore_links = self.get_ignore_link()
for link in dynLinks:
try:
# 跳过非抽奖动态
for ign_lnk in ignore_links:
if ign_lnk in link:
break_flag = 1
if break_flag == 1:
break_flag = 0
continue
break_flag = 0
# 跳过已经入库的
if len(self.draw_dynamic_dao.query_by_dyn_url(remove_query_string(link))) == 0:
self.draw_dynamic_dao.insert(remove_query_string(link), source, note)
cnt = cnt + 1
except Exception as e:
mylogger.error("[dynLinks_to_db 动态插入数据库 出错 %s]" % e, exc_info=True)
self.count = self.count + cnt
self.search_note = self.search_note + note + ":" + str(cnt) + "; "
def get_ignore_link(self):
links = globals.ignore_link
if len(links) != 0:
return links.split('|')
return {}
def init_search(self):
bro = None
try:
bro, chains = init_webdriver()
LoginService(bro, chains, self.user_id).login_by_cookie()
if "你的工具人老公" in globals.ups:
self.searchFromFiftyUps(bro, chains)
if "_大锦鲤_" in globals.ups:
self.searchFromBigFish(bro, chains)
if "Carcinus_" in globals.ups:
self.searchFromCarcinus_(bro, chains)
if "闻不着味" in globals.ups:
self.searchFromSmile(bro, chains)
# 统计入库
self.statistics_dao.insert("", "搜索到的抽奖动态条数为: " + str(self.count), self.search_note)
except:
mylogger.error("[搜索抽奖动态列表主流程 出错]")
finally:
bro.quit()
if __name__ == '__main__':
SearchDynamicByUps().init_search()
================================================
FILE: service/share_service/cancel_share_service.py
================================================
class CancelShareService(object):
def __init__(self):
print()
================================================
FILE: service/share_service/multi_users_share.py
================================================
from service.log_service.log_printer_service import MyLogger
from service.search_draw_dynamic_service.SearchDynamicByUps import SearchDynamicByUps
from service.share_service.share_from_biliLink import BiliLinkShare
from utils import globals
mylogger = MyLogger('multi_users_share.py').getLogger()
class MultiUsersShareService(object):
"""
多用户转发模式
"""
def __init__(self):
mylogger.error('启动多用户转发模式!')
def do_multi_uses_share(self):
try:
users = self.get_multi_uses()
for user in users:
mylogger.error('用户: ' + user + '开始转发动态.')
BiliLinkShare(user).do_share_by_links()
except Exception as e:
mylogger.error("[do_multi_uses_share 多用户模式转发动态 出错 %s]" % e, exc_info=True)
def get_multi_uses(self):
users = globals.multi_users
if len(users) != 0:
return users.split('|')
return {}
================================================
FILE: service/share_service/share_from_biliLink.py
================================================
from datetime import datetime
from dao.draw_dynamic_dao import DrawDynamicDao
from dao.follow_up_dao import FollowUpInfoDao
from dao.init_db import init_db
from dao.share_info_dao import ShareInfoDao
from dao.statistics_dao import StatisticsDao
from service.log_service.log_printer_service import MyLogger
from service.login_service.login_service import LoginService
from service.notify_service.notify_service import NotifyService
from service.remove_msg import RemoveMsgService
from service.share_service.share_one_dynamic import DynamicShareBase
from utils import globals
from utils.globals import get_random_comment_content, get_random_share_content
from utils.ip_util import remove_query_string
from utils.webdriver_util import init_webdriver
mylogger = MyLogger('share_from_biliLick.py').getLogger()
class BiliLinkShare(object):
def __init__(self, user_id, bro=None, chains=None):
db = init_db()
self.share_note = ""
self.user_id = user_id
if bro is None:
self.bro, self.chains = init_webdriver()
else:
self.bro = bro
self.chains = chains
self.share_info_dao = ShareInfoDao(db)
self.follow_up_dao = FollowUpInfoDao(db)
self.draw_dynamic_dao = DrawDynamicDao(db)
self.statistics_dao = StatisticsDao(db)
mylogger.error("启动:根据B站up主的分享链接进行抽奖动态转发!")
def do_share_by_links(self):
do_share_cnt = 0
success_share_cnt = 0
break_flag = 0
try:
LoginService(self.bro, self.chains, self.user_id).login_by_cookie()
datas = self.get_today_dynamic_links()
ignore_links = self.get_ignore_link()
for data in datas:
lucky_dynamic_url = remove_query_string(data['dyn_url'])
# lucky_dynamic_url = 'https://www.bilibili.com/opus/886341319897645089'
for ign_lnk in ignore_links:
if ign_lnk in lucky_dynamic_url:
break_flag = 1
# 跳过已经转发过的
if break_flag == 1:
break_flag = 0
continue
break_flag = 0
shared = self.share_info_dao.query_shareInfo_by_shareUrl(lucky_dynamic_url, self.user_id)
if len(shared) != 0:
continue
do_share_cnt = do_share_cnt + 1
dyn = DynamicShareBase()
dyn.user_id = self.user_id
dyn.share_one(self.bro, self.chains, lucky_dynamic_url, get_random_share_content(), get_random_comment_content())
# 保存转发状态和关注的up主信息
if dyn.share_status == 0:
self.draw_dynamic_dao.update_sharedUrl(url=lucky_dynamic_url, status=1)
self.share_info_dao.insert_shareInfo(dyn)
self.follow_up_dao.saverUpdate(dyn.upId, dyn.upUrl, self.user_id)
success_share_cnt = success_share_cnt + 1
except:
mylogger.error("[do_share_by_links 根据url转发动态 出错]")
finally:
if do_share_cnt == 0:
percentage = 0
else:
percentage = (success_share_cnt / do_share_cnt) * 100
succ_percentage = f"成功率为 : {percentage:.2f}%"
content = " 成功的转发条数为:" + str(success_share_cnt) + ";" + succ_percentage
if 50 > percentage > 0:
NotifyService().fangtang_msg_push_by_content(title="程序预警,需要处理!", content=content)
self.statistics_dao.insert(self.user_id, content, "")
# 暂时停止移除
# RemoveMsgService(self.user_id, success_share_cnt, bro=self.bro, chains=self.chains).do_remove()
self.bro.quit()
def get_ignore_link(self):
links = globals.ignore_link
if len(links) != 0:
return links.split('|')
return {}
def get_today_dynamic_links(self):
"""
从数据库中获取当天的分享链接
:return:
"""
today = str(datetime.now().strftime("%Y-%m-%d"))
return self.draw_dynamic_dao.query_by_time(today, limit=60, status=0)
================================================
FILE: service/share_service/share_one_dynamic.py
================================================
import time
from datetime import datetime
from service.log_service.log_printer_service import MyLogger
from utils.ip_util import get_host_ip, get_partContent_from_lick
from utils.time_util import random_sleep
from utils.webdriver_util import ElementUtil
mylogger = MyLogger('share_one_dynamic.py').getLogger()
class DynamicShareBase(object):
def __init__(self):
# 公有属性,可以在类外部访问
self.upId = None
self.upUrl = None
self.share_url = None
self.status = 1
self.machine_ip = None
self.share_time = None
self.share_status = 1
self.user_id = None
def share_one(self, bro, chains, lucky_dynamic_url, share_content, comment_content):
"""
提供需要转发的抽奖动态URL,然后“执行状态、up主的ID、up主的主页URL”等信息
:param bro:
:param chains:
:param lucky_dynamic_url: 需要进行转发的抽奖动态的URL
:return:
"""
try:
bro.get(lucky_dynamic_url)
bro.refresh()
ElementUtil.wait_to_go(bro)
# 新版转旧版本
self.to_old_version(bro, chains)
# 点击关注
self.click_follow(bro, chains)
random_sleep()
# 点赞
self.click_like(bro, chains)
random_sleep()
# 预约抽奖
self.click_reserve(bro, chains)
random_sleep()
# 评论
self.commit_comment(bro, chains, comment_content)
random_sleep()
# 移动到“分享”按钮, 点击“转发”
self.click_share(bro, chains, share_content)
random_sleep()
# 回填状态
self.share_status = 0
self.status = 0
self.share_url = lucky_dynamic_url
except Exception as e:
mylogger.error("share_one 转发单条动态主流程 出错url : " + lucky_dynamic_url)
finally:
self.share_time = str(datetime.now())
self.machine_ip = get_host_ip()
mylogger.info('单条动态转发--执行结束')
def click_follow(self, bro, chains):
"""
点击关注,并且返回相关的up主信息
:param bro:
:param chains:
:return:
"""
try:
username = ElementUtil.get_element_by_xpath(bro, chains,
'//*[@id="app"]/div[3]/div/div/div[1]/div[2]/div[1]/span')
# 跳转到新页面(up主的主页)
username.click()
ElementUtil.wait_to_go(bro)
bro.switch_to.window(bro.window_handles[-1])
bro.refresh()
random_sleep()
current_url = bro.current_url
user_id = get_partContent_from_lick(current_url)
self.upId = str(user_id)
self.upUrl = 'https://space.bilibili.com/' + self.upId
# 是否包含“已关注”标签
has_followd = ElementUtil.get_element_by_xpath(bro, chains,
'//*[@id="app"]/div[1]/div[1]/div[2]/div[4]/div[1]/div')
if "已关注" not in has_followd.get_attribute('innerText'):
do_follow_btn = ElementUtil.get_element_by_xpath(bro, chains,
'//*[@id="app"]/div[1]/div[1]/div[2]/div[4]/span')
chains.click(do_follow_btn).perform()
bro.close()
bro.switch_to.window(bro.window_handles[-1])
except Exception as e:
mylogger.error("[click_follow 点击“关注” 出错 %s]" % e, exc_info=True)
# 将异常传递给上一级函数
raise
def click_like(self, bro, chains):
"""
点赞
:param bro:
:param chains:
:return:
"""
try:
path = '//*[@id="app"]/div[3]/div[2]/div/div[1]/div[1]'
like_btn_old = ElementUtil.get_element_by_xpath(bro, chains, path)
chains.click(like_btn_old).perform()
except Exception as e:
mylogger.error("[click_like 点击“点赞” 出错 %s]" % e, exc_info=True)
raise
def click_reserve(self, bro, chains):
"""
预约抽奖
:param bro:
:param chains:
:return:
"""
try:
reserve_path = '//*[@id="app"]/div[3]/div[1]/div[1]/div/div[3]/div/div/div[3]/div/div/div[2]/button'
if ElementUtil.is_xpath_exist(bro, chains, reserve_path):
reserve_btn = ElementUtil.get_element_by_xpath(bro, chains, reserve_path)
chains.click(reserve_btn).perform()
except Exception as e:
mylogger.error("[click_like 点击“预约抽奖” 出错 %s]" % e, exc_info=True)
raise
def commit_comment(self, bro, chains, comment_content):
"""
评论
:param comment_content:
:param bro:
:param chains:
:return:
"""
try:
comment_old = ElementUtil.get_element_by_xpath(bro, chains,
'//*[@id="app"]/div[3]/div[1]/div[2]/div[2]/div[1]/div/div/div/div/div[2]/div[1]/div/div[1]/div[2]/div')
chains.click(comment_old).perform()
comment_xx_path = '//*[@id="app"]/div[3]/div[1]/div[2]/div[2]/div[1]/div/div/div/div/div[2]/div[1]/div/div[1]/div[2]/div/textarea'
comment_cont = ElementUtil.get_element_by_xpath(bro, chains,comment_xx_path)
comment_cont.send_keys("" + str(comment_content))
commit_btn_old = ElementUtil.get_element_by_xpath(bro, chains,
'//*[@id="app"]/div[3]/div[1]/div[2]/div[2]/div[1]/div/div/div/div/div[2]/div[1]/div/div[2]/div[2]/div')
chains.click(commit_btn_old).perform()
except Exception as e:
mylogger.error("[commit_comment 点击“评论” 出错 %s]" % e, exc_info=True)
raise
def click_share(self, bro, chains, share_content):
"""
执行转发动态
:param bro:
:param chains:
:return:
"""
try:
share_btn_old = ElementUtil.get_element_by_xpath(bro, chains,
'//*[@id="app"]/div[3]/div[2]/div/div[1]/div[2]')
chains.click(share_btn_old).perform()
share_text_old = ElementUtil.get_element_by_xpath(bro, chains,
'/html/body/div[4]/div[2]/div[1]/div/div[3]/div[1]/div')
share_text_old.send_keys(share_content)
do_share_btn_old = ElementUtil.get_element_by_xpath(bro, chains,
'/html/body/div[4]/div[2]/div[1]/div/div[5]/div[2]/div[2]')
chains.click(do_share_btn_old).perform()
random_sleep()
except Exception as e:
mylogger.error("[click_share 点击“分享” 出错 %s]" % e, exc_info=True)
raise
def to_old_version(self, bro, chains):
"""
新版转旧版
:param bro:
:param chains:
:return:
"""
if ElementUtil.is_xpath_exist(bro, chains, '//*[@id="app"]/div[4]/div[3]/div/div[2]/div[1]') is True:
to_old_btn = ElementUtil.get_element_by_xpath(bro, chains,
'//*[@id="app"]/div[4]/div[3]/div/div[2]/div[1]')
to_old_btn.click()
ElementUtil.wait_to_go(bro)
================================================
FILE: service/statistics_service.py
================================================
from datetime import datetime
from dao.draw_dynamic_dao import DrawDynamicDao
from dao.init_db import init_db
from dao.share_info_dao import ShareInfoDao
from utils import globals
class StatisticsService(object):
def __init__(self):
db = init_db()
self.share_info_dao = ShareInfoDao(db)
self.dyn_dao = DrawDynamicDao(db)
def get_today_searchData(self):
try:
# 获取今天的日期
today = datetime.now()
today_str = today.strftime("%Y-%m-%d")
return self.dyn_dao.query_by_time(today_str, status=1)
except Exception as e:
return {}
def get_today_shareData_by_usrId(self, user_id):
try:
# 获取今天的日期
today = datetime.now()
today_str = today.strftime("%Y-%m-%d")
return self.share_info_dao.query_shareInfo_by_userIdAndTime(user_id, today_str)
except Exception as e:
return {}
def today_data(self):
userIds = self.get_multi_uses()
content = "今日数据汇总: " + "\n\n"
content = content + "1.抽奖动态搜索数量: " + str(len(self.get_today_searchData())) + ";\n\n"
content = content + "2.动态转发情况: " + "\n\n"
for user_id in userIds:
content = content + "\t\t" + user_id + ":" + "成功转发数量:" + str(len(self.get_today_shareData_by_usrId(user_id))) + ";\n\n"
content = content + "\n\n"
cnt = len(userIds)
return cnt, content
def get_multi_uses(self):
users = globals.multi_users
if len(users) != 0:
return users.split('|')
return {}
================================================
FILE: utils/file_util.py
================================================
def get_value_from_env(file_path, key):
with open(file_path, "r") as f:
for line in f:
# 去除换行符和空格,并以等号分割键值对
key_value = line.strip().split("=")
if len(key_value) == 2 and key_value[0] == key:
return key_value[1]
return None
def append_data_to_env(key, data_to_append):
# 读取.env文件内容
with open(".env", "r") as f:
lines = f.readlines()
# 查找包含key的行并在等号后面追加内容
with open(".env", "w") as f:
for line in lines:
if line.strip().startswith(f"{key}="):
line = f"{key}={line.strip().split('=')[1]}{data_to_append}\n"
f.write(line)
================================================
FILE: utils/globals.py
================================================
import os
import random
from dotenv import load_dotenv
from utils.ip_util import get_host_ip
# 加载 .env 文件
load_dotenv()
# 读取变量
max_checks = int(os.getenv("max_checks"))
home_url = os.getenv("home_url")
my_user_id = os.getenv("my_user_id")
ignore_link = os.getenv("ignore_link")
multi_users = os.getenv("multi_users")
do_type = os.getenv("do_type")
is_remove = os.getenv("is_remove")
remove_cnt = os.getenv("remove_cnt")
cookie_value = os.getenv("cookie_value")
# 读取变量
dbname = os.getenv("MYSQL_DATABASE")
user = os.getenv("MYSQL_USER")
passwd = os.getenv("MYSQL_PASSWORD")
root_passwd = os.getenv("MYSQL_ROOT_PASSWORD")
port = int(os.getenv("PORT"))
charset = 'utf8'
notify_switch = os.getenv("notify_switch")
FangTang_KEY = os.getenv("FangTang_KEY")
DRIVER_VERSION = os.getenv("DRIVER_VERSION")
def getHost():
host = get_infos("DB_HOST")
print(host)
if len(host) != 0:
return host
return get_host_ip()
def get_infos(str):
users = os.getenv(str)
return users
def get_random_comment_content():
comments = get_multi_infos("comment_content")
return get_random_from_list(comments)
def get_random_share_content():
shares = get_multi_infos("share_content")
return get_random_from_list(shares)
def get_multi_infos(str):
users = os.getenv(str)
if len(users) != 0:
return users.split('|')
return {}
def get_random_from_list(list):
if len(list) != 0:
return random.choice(list)
return "_"
share_content = get_random_share_content()
comment_content = get_random_comment_content()
ups = get_multi_infos("ups")
db_host = getHost()
selenium_url = "http://" + getHost() + ":5555"
if __name__ == '__main__':
print(db_host)
print(selenium_url)
================================================
FILE: utils/ip_util.py
================================================
import socket
def get_host_ip():
"""
查询本机ip地址
:return: ip
"""
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
ip = s.getsockname()[0]
finally:
s.close()
return ip
def get_partContent_from_lick(current_url):
user_id = '0'
parts = current_url.split('/')
if len(parts) > 1:
user_id = parts[3]
return user_id
def remove_query_string(url):
question_mark_index = url.find('?')
if question_mark_index != -1:
# 如果包含问号,则去掉问号及其后面的内容
url_without_query = url[:question_mark_index]
return url_without_query
else:
# 如果不包含问号,则返回原始url
return url
================================================
FILE: utils/mysql_operate.py
================================================
import pymysql
class MysqldbHelper():
def __init__(self, config):
self.host = config['host']
self.username = config['user']
self.password = config['passwd']
self.port = config['port']
self.con = None
self.cur = None
try:
self.con = pymysql.connect(**config)
self.con.autocommit(1)
# 所有的查询,都在连接 con 的一个模块 cursor 上面运行的
self.cur = self.con.cursor()
except:
print("DataBase connect error,please check the db config.")
# 关闭数据库连接
def close(self):
if not self.con:
self.con.close()
else:
print("DataBase doesn't connect,close connectiong error;please check the db config.")
# 创建数据库
def createDataBase(self, DB_NAME):
# 创建数据库
self.cur.execute(
'CREATE DATABASE IF NOT EXISTS %s DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci' % DB_NAME)
self.con.select_db(DB_NAME)
print('creatDatabase:' + DB_NAME)
# 选择数据库
def selectDataBase(self, DB_NAME):
self.con.select_db(DB_NAME)
# 获取数据库版本号
def getVersion(self):
self.cur.execute("SELECT VERSION()")
return self.getOneData()
# 获取上个查询的结果
def getOneData(self):
# 取得上个查询的结果,是单个结果
data = self.cur.fetchone()
return data
# 创建数据库表
def creatTable(self, tablename, attrdict, constraint):
"""创建数据库表
args:
tablename :表名字
attrdict :属性键值对,{'book_name':'varchar(200) NOT NULL'...}
constraint :主外键约束,PRIMARY KEY(`id`)
"""
# 判断表是否存在
if self.isExistTable(tablename):
print("%s is exit" % tablename)
return
sql = ''
sql_mid = '`id` bigint(11) NOT NULL AUTO_INCREMENT,'
for attr, value in attrdict.items():
sql_mid = sql_mid + '`' + attr + '`' + ' ' + value + ','
sql = sql + 'CREATE TABLE IF NOT EXISTS %s (' % tablename
sql = sql + sql_mid
sql = sql + constraint
sql = sql + ') ENGINE=InnoDB DEFAULT CHARSET=utf8'
print('creatTable:' + sql)
self.executeCommit(sql)
def executeSql(self, sql=''):
"""执行sql语句,针对读操作返回结果集
args:
sql :sql语句
"""
try:
self.cur.execute(sql)
records = self.cur.fetchall()
return records
except pymysql.Error as e:
error = 'MySQL execute failed! ERROR (%s): %s' % (e.args[0], e.args[1])
print(error)
def executeCommit(self, sql=''):
"""执行数据库sql语句,针对更新,删除,事务等操作失败时回滚
"""
try:
self.cur.execute(sql)
self.con.commit()
except pymysql.Error as e:
self.con.rollback()
error = 'MySQL execute failed! ERROR (%s): %s' % (e.args[0], e.args[1])
print("error:", error)
return error
def insert(self, tablename, params):
"""创建数据库表
args:
tablename :表名字
key :属性键
value :属性值
"""
key = []
value = []
for tmpkey, tmpvalue in params.items():
key.append(tmpkey)
if isinstance(tmpvalue, str):
value.append("\'" + tmpvalue + "\'")
else:
value.append(tmpvalue)
attrs_sql = '(' + ','.join(key) + ')'
values_sql = ' values(' + ','.join(value) + ')'
sql = 'insert into %s' % tablename
sql = sql + attrs_sql + values_sql
print('_insert:' + sql)
self.executeCommit(sql)
def select(self, tablename, cond_dict='', order='', fields='*'):
"""查询数据
args:
tablename :表名字
cond_dict :查询条件
order :排序条件
example:
print mydb.select(table)
print mydb.select(table, fields=["name"])
print mydb.select(table, fields=["name", "age"])
print mydb.select(table, fields=["age", "name"])
"""
consql = ' '
if cond_dict != '':
for k, v in cond_dict.items():
consql = consql + '`' + k + '`' + '=' + '"' + v + '"' + ' and'
consql = consql + ' 1=1 '
if fields == "*":
sql = 'select * from %s where ' % tablename
else:
if isinstance(fields, list):
fields = ",".join(fields)
sql = 'select %s from %s where ' % (fields, tablename)
else:
print("fields input error, please input list fields.")
sql = sql + consql + order
print('select:' + sql)
return self.executeSql(sql)
def insertMany(self, table, attrs, values):
"""插入多条数据
args:
tablename :表名字
attrs :属性键
values :属性值
example:
table='test_mysqldb'
key = ["id" ,"name", "age"]
value = [[101, "liuqiao", "25"], [102,"liuqiao1", "26"], [103 ,"liuqiao2", "27"], [104 ,"liuqiao3", "28"]]
mydb.insertMany(table, key, value)
"""
values_sql = ['%s' for v in attrs]
attrs_sql = '(' + ','.join(attrs) + ')'
values_sql = ' values(' + ','.join(values_sql) + ')'
sql = 'insert into %s' % table
sql = sql + attrs_sql + values_sql
print('insertMany:' + sql)
try:
print(sql)
for i in range(0, len(values), 20000):
self.cur.executemany(sql, values[i:i + 20000])
self.con.commit()
except pymysql.Error as e:
self.con.rollback()
error = 'insertMany executemany failed! ERROR (%s): %s' % (e.args[0], e.args[1])
print(error)
raise
def delete(self, tablename, cond_dict):
"""删除数据
args:
tablename :表名字
cond_dict :删除条件字典
example:
params = {"name" : "caixinglong", "age" : "38"}
mydb.delete(table, params)
"""
consql = ' '
if cond_dict != '':
for k, v in cond_dict.items():
if isinstance(v, str):
v = "\'" + v + "\'"
consql = consql + tablename + "." + k + '=' + v + ' and '
consql = consql + ' 1=1 '
sql = "DELETE FROM %s where%s" % (tablename, consql)
print(sql)
return self.executeCommit(sql)
def update(self, tablename, attrs_dict, cond_dict):
"""更新数据
args:
tablename :表名字
attrs_dict :更新属性键值对字典
cond_dict :更新条件字典
example:
params = {"name" : "caixinglong", "age" : "38"}
cond_dict = {"name" : "liuqiao", "age" : "18"}
mydb.update(table, params, cond_dict)
"""
attrs_list = []
consql = ' '
for tmpkey, tmpvalue in attrs_dict.items():
attrs_list.append("`" + tmpkey + "`" + "=" + "\'" + tmpvalue + "\'")
attrs_sql = ",".join(attrs_list)
print("attrs_sql:", attrs_sql)
if cond_dict != '':
for k, v in cond_dict.items():
if isinstance(v, str):
v = "\'" + v + "\'"
consql = consql + "`" + tablename + "`." + "`" + k + "`" + '=' + v + ' and '
consql = consql + ' 1=1 '
sql = "UPDATE %s SET %s where%s" % (tablename, attrs_sql, consql)
print(sql)
return self.executeCommit(sql)
def dropTable(self, tablename):
"""删除数据库表
args:
tablename :表名字
"""
sql = "DROP TABLE %s" % tablename
self.executeCommit(sql)
def deleteTable(self, tablename):
"""清空数据库表
args:
tablename :表名字
"""
sql = "DELETE FROM %s" % tablename
print("sql=", sql)
self.executeCommit(sql)
# def isExistTable(self, tablename):
# """判断数据表是否存在
#
# args:
# tablename :表名字
#
# Return:
# 存在返回True,不存在返回False
# """
# sql = "select * from %s" % tablename
# result = self.executeCommit(sql)
# if result is None:
# return True
# else:
# if re.search("doesn't exist", result):
# return False
# else:
# return True
def select_db(self, sql):
"""查询"""
# 检查连接是否断开,如果断开就进行重连
self.con.ping(reconnect=True)
# 使用 execute() 执行sql
self.cur.execute(sql)
# 使用 fetchall() 获取查询结果
data = self.cur.fetchall()
return data
def __del__(self): # 对象资源被释放时触发,在对象即将被删除时的最后操作
# 关闭游标
self.cur.close()
# 关闭数据库连接
self.con.close()
def execute_db(self, sql):
"""更新/新增/删除"""
try:
# 检查连接是否断开,如果断开就进行重连
self.con.ping(reconnect=True)
# 使用 execute() 执行sql
self.cur.execute(sql)
# 提交事务
self.con.commit()
return "插入成功"
except Exception as e:
# 回滚所有更改
self.con.rollback()
return "操作出现错误"
================================================
FILE: utils/time_util.py
================================================
from datetime import datetime
import random
import time
def deal_time(sj):
if "小时" in sj or "分钟" in sj or "刚刚" in sj:
return datetime.time.strftime("%Y-%m-%d", time.localtime(time.time()))
if len(sj) == 5:
return '2023-' + sj
return sj;
def random_sleep(start=1, end=5):
# 生成随机的睡眠时间,范围为1到5秒
sleep_time = random.randint(start, end)
# print("休眠时间" +str(sleep_time))
# 进行睡眠操作
time.sleep(sleep_time)
if __name__ == '__main__':
print(datetime.now())
random_sleep()
print(datetime.now())
random_sleep()
print(datetime.now())
random_sleep()
print(datetime.now())
random_sleep()
print(datetime.now())
================================================
FILE: utils/webdriver_util.py
================================================
from selenium.webdriver.support.wait import WebDriverWait
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver import ChromeOptions
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from utils import globals
class ElementUtil(object):
def get_element_by_xpath(bro, chains, path):
"""
获取element的通用方法
:param bro:
:param chains:
:param path:
:return:
"""
return WebDriverWait(bro, 10).until(EC.element_to_be_clickable((By.XPATH, path)))
def get_elementArr_by_xpath(bro, chains, path):
return WebDriverWait(bro, 10).until(EC.presence_of_all_elements_located((By.XPATH, path)))
def is_xpath_exist(bro, chains, path):
try:
WebDriverWait(bro, 5).until(EC.element_to_be_clickable((By.XPATH, path)))
return True
except:
return False
def wait_to_go(bro, timeout=10):
WebDriverWait(bro, timeout).until(EC.new_window_is_opened)
def local_driver():
chrome_options = webdriver.ChromeOptions()
# chrome_options.add_argument("--headless") # 以无头模式运行Chrome
chrome_options.add_argument("--no-sandbox") # 取消沙盒模式
chrome_options.add_argument("--disable-gpu") # 取消GPU
chrome_options.add_argument("--disable-extensions") # 禁用插件加载
chrome_options.add_argument("--disable-software-rasterizer") # 禁用软件光栅化器
chrome_options.add_argument('lang=zh_CN.UTF-8')
chrome_options.add_argument('--enable-javascript')
chrome_options.add_argument("--start-minimized")
chrome_options.add_argument(
'--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/115.0.5790.110 Safari/537.36') # 替换User-Agent
option = ChromeOptions()
option.add_experimental_option('excludeSwitches', ['enable-automation'])
s = Service(r"./lib/chromedriver.exe")
bro = webdriver.Chrome(service=s, chrome_options=chrome_options, options=option)
chains = ActionChains(bro)
return bro, chains
def online_driver():
"""
初始化Selenium信息———— 此版本用于生成Cookie,所以浏览器去掉无头模式
:return:
"""
# 设置浏览器信息
chrome_options = webdriver.ChromeOptions()
# chrome_options.add_argument("--headless") # 以无头模式运行Chrome
chrome_options.add_argument("--no-sandbox") # 取消沙盒模式
chrome_options.add_argument("--disable-gpu") # 取消GPU
chrome_options.add_argument("--disable-software-rasterizer")
# chrome_options.add_argument("blink-settings=imagesEnabled=false") # 配置不加载图片
chrome_options.add_argument("--disable-extensions") # 禁用插件加载
chrome_options.add_argument('lang=zh_CN.UTF-8')
chrome_options.add_argument(
'--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/101.0.4951.64 Safari/537.36') # 替换User-Agent
driver = webdriver.Remote(
command_executor=globals.selenium_url,
options=chrome_options
)
chains = ActionChains(driver)
return driver, chains
def init_webdriver():
if globals.DRIVER_VERSION == 'Local':
return local_driver()
if globals.DRIVER_VERSION == 'Online':
return online_driver()
# 默认本地驱动
return local_driver()
gitextract_ibvvi1vh/
├── .dockerignore
├── .github/
│ └── ISSUE_TEMPLATE/
│ ├── 1.bug.yml
│ └── 2.feature.yml
├── .gitignore
├── Dockerfile
├── LICENSE
├── Other.md
├── Readme.md
├── dao/
│ ├── common_dao.py
│ ├── draw_dynamic_dao.py
│ ├── follow_up_dao.py
│ ├── init_db.py
│ ├── share_info_dao.py
│ ├── shared_url_dao.py
│ └── statistics_dao.py
├── docker-compose.yml
├── lib/
│ └── init_db_script.sql
├── main.py
├── notify.py
├── requirements.txt
├── service/
│ ├── follow_service/
│ │ └── cancel_follow_service.py
│ ├── log_service/
│ │ ├── TextHandler.py
│ │ └── log_printer_service.py
│ ├── login_service/
│ │ ├── check_login_status.py
│ │ └── login_service.py
│ ├── notify_service/
│ │ └── notify_service.py
│ ├── remove_msg.py
│ ├── remove_share.py
│ ├── search_draw_dynamic_service/
│ │ └── SearchDynamicByUps.py
│ ├── share_service/
│ │ ├── cancel_share_service.py
│ │ ├── multi_users_share.py
│ │ ├── share_from_biliLink.py
│ │ └── share_one_dynamic.py
│ └── statistics_service.py
└── utils/
├── file_util.py
├── globals.py
├── ip_util.py
├── mysql_operate.py
├── time_util.py
└── webdriver_util.py
SYMBOL INDEX (144 symbols across 29 files)
FILE: dao/common_dao.py
class CommonDao (line 4) | class CommonDao(object):
method __init__ (line 5) | def __init__(self, db):
method common_query (line 8) | def common_query(self, table_name="", cond_dict="", order="", fields="...
method common_insertMany (line 20) | def common_insertMany(self, table, attrs, values):
FILE: dao/draw_dynamic_dao.py
class DrawDynamicDao (line 4) | class DrawDynamicDao(object):
method __init__ (line 5) | def __init__(self, db):
method query_by_time (line 9) | def query_by_time(self, time, limit=2000, status=1):
method query_by_dyn_url (line 20) | def query_by_dyn_url(self, dyn_url):
method insert (line 28) | def insert(self, dyn_url, source, note):
method update_sharedUrl (line 41) | def update_sharedUrl(self, url, status):
FILE: dao/follow_up_dao.py
class FollowUpInfoDao (line 3) | class FollowUpInfoDao(object):
method __init__ (line 4) | def __init__(self,db):
method query_followUpInfo_by_UpId (line 8) | def query_followUpInfo_by_UpId(self, up_id, user_id):
method saverUpdate (line 17) | def saverUpdate(self, up_id, up_url, user_id):
FILE: dao/init_db.py
function init_db (line 10) | def init_db():
FILE: dao/share_info_dao.py
class ShareInfoDao (line 5) | class ShareInfoDao(object):
method __init__ (line 6) | def __init__(self, db):
method query_shareInfo_by_userIdAndTime (line 10) | def query_shareInfo_by_userIdAndTime(self, user_id, share_time):
method query_shareInfo_by_shareUrl (line 24) | def query_shareInfo_by_shareUrl(self, share_url, user_id):
method insert_shareInfo (line 39) | def insert_shareInfo(self, shareInfo):
FILE: dao/shared_url_dao.py
class SharedUrlDao (line 7) | class SharedUrlDao(object):
method __init__ (line 8) | def __init__(self, db):
method query_sharedUrls_limit (line 12) | def query_sharedUrls_limit(self, user_id, status, limit):
method insert_sharedUrl (line 30) | def insert_sharedUrl(self, user_id, url):
method update_sharedUrl (line 37) | def update_sharedUrl(self, user_id, url, status):
FILE: dao/statistics_dao.py
class StatisticsDao (line 6) | class StatisticsDao(object):
method __init__ (line 7) | def __init__(self, db):
method query_by_time (line 11) | def query_by_time(self, time):
method query_today_data (line 21) | def query_today_data(self):
method insert (line 36) | def insert(self, user_id, content, note):
FILE: lib/init_db_script.sql
type t_draw_dynamic (line 4) | create table t_draw_dynamic
type t_followdups (line 15) | create table t_followdups
type t_prize (line 27) | create table t_prize
type t_share_info (line 37) | create table t_share_info
type t_statistics (line 63) | create table t_statistics
FILE: main.py
function do_search (line 8) | def do_search():
function do_share (line 10) | def do_share():
FILE: service/follow_service/cancel_follow_service.py
class CancelFollowService (line 3) | class CancelFollowService(object):
method __init__ (line 5) | def __init__(self):
FILE: service/log_service/TextHandler.py
class TextHandler (line 5) | class TextHandler(logging.Handler):
method __init__ (line 6) | def __init__(self, text_widget):
method emit (line 10) | def emit(self, record):
FILE: service/log_service/log_printer_service.py
class MyLogger (line 6) | class MyLogger(object):
method __init__ (line 8) | def __init__(self, name=None):
method getLogger (line 29) | def getLogger(self):
method print_run_time (line 32) | def print_run_time(self, name, begin_time, end_time):
FILE: service/login_service/check_login_status.py
function check_cookie_status (line 8) | def check_cookie_status():
FILE: service/login_service/login_service.py
class LoginService (line 14) | class LoginService(object):
method __init__ (line 15) | def __init__(self, bro, chains, my_user_id='0'):
method login_manual (line 21) | def login_manual(self):
method login_by_cookie (line 40) | def login_by_cookie(self):
method login_by_cookie2 (line 58) | def login_by_cookie2(self):
FILE: service/notify_service/notify_service.py
class NotifyService (line 7) | class NotifyService(object):
method __init__ (line 9) | def __init__(self):
method fangtang_msg_push (line 14) | def fangtang_msg_push(self):
method fangtang_msg_push_by_content (line 28) | def fangtang_msg_push_by_content(self, title="", content=""):
FILE: service/remove_msg.py
class RemoveMsgService (line 14) | class RemoveMsgService(object):
method __init__ (line 19) | def __init__(self, user_id, cnt, bro, chains):
method do_remove (line 26) | def do_remove(self):
FILE: service/remove_share.py
class RemoveShareService (line 16) | class RemoveShareService(object):
method __init__ (line 21) | def __init__(self, user_id, cnt=None, bro=None, chains=None):
method get_expired_url (line 34) | def get_expired_url(self, scroll_cnt):
method do_remove (line 67) | def do_remove(self):
method remove_one (line 80) | def remove_one(self, lucky_dynamic_url):
method click_delete (line 99) | def click_delete(self, bro, chains):
method quilt_bro (line 126) | def quilt_bro(self):
method start_remove_service (line 129) | def start_remove_service(self):
FILE: service/search_draw_dynamic_service/SearchDynamicByUps.py
class SearchDynamicByUps (line 19) | class SearchDynamicByUps(object):
method __init__ (line 21) | def __init__(self, user_id):
method searchFromFiftyUps (line 30) | def searchFromFiftyUps(self, bro, chains):
method searchFromBigFish (line 61) | def searchFromBigFish(self, bro, chains):
method searchFromCarcinus_ (line 89) | def searchFromCarcinus_(self, bro, chains):
method searchFromSmile (line 116) | def searchFromSmile(self, bro, chains):
method find_first_ele (line 143) | def find_first_ele(self, bro, chains):
method dynLinks_to_db (line 155) | def dynLinks_to_db(self, dynLinks, source, note):
method get_ignore_link (line 178) | def get_ignore_link(self):
method init_search (line 184) | def init_search(self):
FILE: service/share_service/cancel_share_service.py
class CancelShareService (line 2) | class CancelShareService(object):
method __init__ (line 4) | def __init__(self):
FILE: service/share_service/multi_users_share.py
class MultiUsersShareService (line 9) | class MultiUsersShareService(object):
method __init__ (line 14) | def __init__(self):
method do_multi_uses_share (line 18) | def do_multi_uses_share(self):
method get_multi_uses (line 27) | def get_multi_uses(self):
FILE: service/share_service/share_from_biliLink.py
class BiliLinkShare (line 21) | class BiliLinkShare(object):
method __init__ (line 22) | def __init__(self, user_id, bro=None, chains=None):
method do_share_by_links (line 37) | def do_share_by_links(self):
method get_ignore_link (line 85) | def get_ignore_link(self):
method get_today_dynamic_links (line 91) | def get_today_dynamic_links(self):
FILE: service/share_service/share_one_dynamic.py
class DynamicShareBase (line 11) | class DynamicShareBase(object):
method __init__ (line 13) | def __init__(self):
method share_one (line 24) | def share_one(self, bro, chains, lucky_dynamic_url, share_content, com...
method click_follow (line 64) | def click_follow(self, bro, chains):
method click_like (line 98) | def click_like(self, bro, chains):
method click_reserve (line 114) | def click_reserve(self, bro, chains):
method commit_comment (line 130) | def commit_comment(self, bro, chains, comment_content):
method click_share (line 152) | def click_share(self, bro, chains, share_content):
method to_old_version (line 174) | def to_old_version(self, bro, chains):
FILE: service/statistics_service.py
class StatisticsService (line 8) | class StatisticsService(object):
method __init__ (line 10) | def __init__(self):
method get_today_searchData (line 15) | def get_today_searchData(self):
method get_today_shareData_by_usrId (line 24) | def get_today_shareData_by_usrId(self, user_id):
method today_data (line 33) | def today_data(self):
method get_multi_uses (line 45) | def get_multi_uses(self):
FILE: utils/file_util.py
function get_value_from_env (line 2) | def get_value_from_env(file_path, key):
function append_data_to_env (line 12) | def append_data_to_env(key, data_to_append):
FILE: utils/globals.py
function getHost (line 33) | def getHost():
function get_infos (line 41) | def get_infos(str):
function get_random_comment_content (line 46) | def get_random_comment_content():
function get_random_share_content (line 51) | def get_random_share_content():
function get_multi_infos (line 56) | def get_multi_infos(str):
function get_random_from_list (line 63) | def get_random_from_list(list):
FILE: utils/ip_util.py
function get_host_ip (line 3) | def get_host_ip():
function get_partContent_from_lick (line 17) | def get_partContent_from_lick(current_url):
function remove_query_string (line 24) | def remove_query_string(url):
FILE: utils/mysql_operate.py
class MysqldbHelper (line 3) | class MysqldbHelper():
method __init__ (line 5) | def __init__(self, config):
method close (line 22) | def close(self):
method createDataBase (line 29) | def createDataBase(self, DB_NAME):
method selectDataBase (line 37) | def selectDataBase(self, DB_NAME):
method getVersion (line 41) | def getVersion(self):
method getOneData (line 46) | def getOneData(self):
method creatTable (line 52) | def creatTable(self, tablename, attrdict, constraint):
method executeSql (line 74) | def executeSql(self, sql=''):
method executeCommit (line 88) | def executeCommit(self, sql=''):
method insert (line 101) | def insert(self, tablename, params):
method select (line 124) | def select(self, tablename, cond_dict='', order='', fields='*'):
method insertMany (line 155) | def insertMany(self, table, attrs, values):
method delete (line 186) | def delete(self, tablename, cond_dict):
method update (line 209) | def update(self, tablename, attrs_dict, cond_dict):
method dropTable (line 239) | def dropTable(self, tablename):
method deleteTable (line 248) | def deleteTable(self, tablename):
method select_db (line 278) | def select_db(self, sql):
method __del__ (line 288) | def __del__(self): # 对象资源被释放时触发,在对象即将被删除时的最后操作
method execute_db (line 294) | def execute_db(self, sql):
FILE: utils/time_util.py
function deal_time (line 5) | def deal_time(sj):
function random_sleep (line 13) | def random_sleep(start=1, end=5):
FILE: utils/webdriver_util.py
class ElementUtil (line 12) | class ElementUtil(object):
method get_element_by_xpath (line 13) | def get_element_by_xpath(bro, chains, path):
method get_elementArr_by_xpath (line 23) | def get_elementArr_by_xpath(bro, chains, path):
method is_xpath_exist (line 26) | def is_xpath_exist(bro, chains, path):
method wait_to_go (line 33) | def wait_to_go(bro, timeout=10):
function local_driver (line 36) | def local_driver():
function online_driver (line 57) | def online_driver():
function init_webdriver (line 81) | def init_webdriver():
Condensed preview — 40 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (121K chars).
[
{
"path": ".dockerignore",
"chars": 157,
"preview": ".git\n.gitignore\n.dockerignore\n.github\n.DS_Store\n\nDockerfile\ndocker-compose.yml\n\nREADME.md\nOther.md\nLICENSE\n\n.vscode\n.ide"
},
{
"path": ".github/ISSUE_TEMPLATE/1.bug.yml",
"chars": 1354,
"preview": "name: Bug report 🐛\ndescription: 项目运行中遇到的Bug或问题。\nlabels: [\"status: issue-bug\"]\nbody:\n - type: checkboxes\n attributes:"
},
{
"path": ".github/ISSUE_TEMPLATE/2.feature.yml",
"chars": 759,
"preview": "name: Feature request 🚀\ndescription: 提出你对项目的新想法或建议。\nlabels: [\"status: issue-feature\"]\nbody:\n - type: markdown\n attri"
},
{
"path": ".gitignore",
"chars": 82,
"preview": "pyvenv\n.idea\nLog\n\n\n__pycache__\n*/__pycache__\n/service/*/__pycache__\n/*/__pycache__"
},
{
"path": "Dockerfile",
"chars": 216,
"preview": "FROM python:3\n\n# 复制项目文件到容器中\nCOPY . /app\n\n# 设置工作目录为项目目录\nWORKDIR /app\n\n# 安装项目依赖项\nRUN pip install -r requirements.txt -i ht"
},
{
"path": "LICENSE",
"chars": 35149,
"preview": " GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
},
{
"path": "Other.md",
"chars": 534,
"preview": "## <a id=\"debug_doc\">Windows系统调试本程序</a>\n\n### 环境准备\n\n:\n def __init__(self, db):\n self.db = db\n\n def com"
},
{
"path": "dao/draw_dynamic_dao.py",
"chars": 1592,
"preview": "from datetime import datetime\n\n\nclass DrawDynamicDao(object):\n def __init__(self, db):\n self.table_name = 't_d"
},
{
"path": "dao/follow_up_dao.py",
"chars": 1335,
"preview": "from datetime import datetime\n\nclass FollowUpInfoDao(object):\n def __init__(self,db):\n self.db = None\n "
},
{
"path": "dao/init_db.py",
"chars": 626,
"preview": "import logging\n\nimport pymysql\n\nfrom utils.mysql_operate import MysqldbHelper\n\nfrom utils.globals import db_host, port, "
},
{
"path": "dao/share_info_dao.py",
"chars": 2066,
"preview": "from dao.init_db import init_db\nfrom service.share_service.share_one_dynamic import DynamicShareBase\n\n\nclass ShareInfoDa"
},
{
"path": "dao/shared_url_dao.py",
"chars": 1422,
"preview": "from datetime import datetime\n\nfrom dao.init_db import init_db\nfrom service.share_service.share_one_dynamic import Dynam"
},
{
"path": "dao/statistics_dao.py",
"chars": 1342,
"preview": "from datetime import datetime, timedelta\n\nfrom dao.init_db import init_db\n\n\nclass StatisticsDao(object):\n def __init_"
},
{
"path": "docker-compose.yml",
"chars": 1002,
"preview": "\n\nversion: '3'\nservices:\n bili-db:\n image: mysql:5.7\n container_name: bili-db\n environment:\n MYSQL_ROOT_P"
},
{
"path": "lib/init_db_script.sql",
"chars": 1930,
"preview": "-- create database luckybili default character set utf8mb4 collate utf8mb4_general_ci;\nuse luckybili;\n\ncreate table t_dr"
},
{
"path": "main.py",
"chars": 688,
"preview": "import time\nimport schedule\nfrom service.search_draw_dynamic_service.SearchDynamicByUps import SearchDynamicByUps\nfrom s"
},
{
"path": "notify.py",
"chars": 482,
"preview": "from service.notify_service.notify_service import NotifyService\nfrom service.remove_share import RemoveShareService\nfrom"
},
{
"path": "service/follow_service/cancel_follow_service.py",
"chars": 77,
"preview": "\n\nclass CancelFollowService(object):\n\n def __init__(self):\n print()"
},
{
"path": "service/log_service/TextHandler.py",
"chars": 438,
"preview": "import logging\nimport tkinter as tk\n\n\nclass TextHandler(logging.Handler):\n def __init__(self, text_widget):\n s"
},
{
"path": "service/log_service/log_printer_service.py",
"chars": 1718,
"preview": "import logging\nimport time\nimport os\n\n\nclass MyLogger(object):\n\n def __init__(self, name=None):\n self.name = n"
},
{
"path": "service/login_service/check_login_status.py",
"chars": 551,
"preview": "import logging\nimport os\nfrom utils.file_util import get_value_from_env\n\nlogging.basicConfig(level=logging.INFO)\n\n\ndef c"
},
{
"path": "service/login_service/login_service.py",
"chars": 2904,
"preview": "import json\nfrom time import sleep\nfrom urllib.parse import urlparse\nfrom selenium.webdriver.common.by import By\nfrom se"
},
{
"path": "service/notify_service/notify_service.py",
"chars": 1286,
"preview": "import requests\n\nfrom dao.init_db import init_db\nfrom dao.statistics_dao import StatisticsDao\nfrom utils import globals\n"
},
{
"path": "service/remove_msg.py",
"chars": 1812,
"preview": "import time\n\nfrom selenium.webdriver import ActionChains, Keys\n\nfrom service.log_service.log_printer_service import MyLo"
},
{
"path": "service/remove_share.py",
"chars": 5244,
"preview": "import time\n\nfrom selenium.webdriver import ActionChains, Keys\n\nfrom dao.init_db import init_db\nfrom dao.shared_url_dao "
},
{
"path": "service/search_draw_dynamic_service/SearchDynamicByUps.py",
"chars": 8988,
"preview": "import time\nfrom datetime import datetime\n\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom seleniu"
},
{
"path": "service/share_service/cancel_share_service.py",
"chars": 75,
"preview": "\nclass CancelShareService(object):\n\n def __init__(self):\n print()"
},
{
"path": "service/share_service/multi_users_share.py",
"chars": 932,
"preview": "from service.log_service.log_printer_service import MyLogger\nfrom service.search_draw_dynamic_service.SearchDynamicByUps"
},
{
"path": "service/share_service/share_from_biliLink.py",
"chars": 4120,
"preview": "from datetime import datetime\n\nfrom dao.draw_dynamic_dao import DrawDynamicDao\nfrom dao.follow_up_dao import FollowUpInf"
},
{
"path": "service/share_service/share_one_dynamic.py",
"chars": 7153,
"preview": "import time\nfrom datetime import datetime\nfrom service.log_service.log_printer_service import MyLogger\nfrom utils.ip_uti"
},
{
"path": "service/statistics_service.py",
"chars": 1602,
"preview": "from datetime import datetime\nfrom dao.draw_dynamic_dao import DrawDynamicDao\nfrom dao.init_db import init_db\nfrom dao.s"
},
{
"path": "utils/file_util.py",
"chars": 662,
"preview": "\ndef get_value_from_env(file_path, key):\n with open(file_path, \"r\") as f:\n for line in f:\n # 去除换行符和"
},
{
"path": "utils/globals.py",
"chars": 1738,
"preview": "import os\nimport random\n\nfrom dotenv import load_dotenv\n\nfrom utils.ip_util import get_host_ip\n\n# 加载 .env 文件\nload_dotenv"
},
{
"path": "utils/ip_util.py",
"chars": 707,
"preview": "import socket\n\ndef get_host_ip():\n \"\"\"\n 查询本机ip地址\n :return: ip\n \"\"\"\n try:\n s = socket.socket(socket"
},
{
"path": "utils/mysql_operate.py",
"chars": 9397,
"preview": "import pymysql\n\nclass MysqldbHelper():\n\n def __init__(self, config):\n self.host = config['host']\n self."
},
{
"path": "utils/time_util.py",
"chars": 685,
"preview": "from datetime import datetime\nimport random\nimport time\n\ndef deal_time(sj):\n if \"小时\" in sj or \"分钟\" in sj or \"刚刚\" in s"
},
{
"path": "utils/webdriver_util.py",
"chars": 3385,
"preview": "from selenium.webdriver.support.wait import WebDriverWait\nfrom selenium import webdriver\nfrom selenium.webdriver import "
}
]
// ... and 1 more files (download for full content)
About this extraction
This page contains the full source code of the rongchenlin/BiliBili-Lucky-Draw GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 40 files (106.1 KB), approximately 27.7k tokens, and a symbol index with 144 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.