Skip to content

Commit dafc124

Browse files
committed
Added three bots in the bots directory
0 parents  commit dafc124

File tree

550 files changed

+120885
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

550 files changed

+120885
-0
lines changed

.gitignore

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
TwiiterAPI.txt
2+
__pycache__
3+
testAuth.py

bots/autoreply.py

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
#!/usr/bin/env python
2+
# twitterBot/bots/autoreply.py
3+
4+
import tweepy
5+
import logging
6+
from config import create_api
7+
import time
8+
9+
logging.basicConfig(level=logging.INFO)
10+
logger = logging.getLogger()
11+
12+
def check_mentions(api, keywords, since_id):
13+
logger.info("Retrieving mentions")
14+
new_since_id = since_id
15+
for tweet in tweepy.Cursor(api.mentions_timeline,
16+
since_id=since_id).items():
17+
new_since_id = max(tweet.id, new_since_id)
18+
if tweet.in_reply_to_status_id is not None:
19+
continue
20+
if any(keyword in tweet.text.lower() for keyword in keywords):
21+
logger.info(f"Answering to {tweet.user.name}")
22+
23+
if not tweet.user.following:
24+
tweet.user.follow()
25+
26+
api.update_status(
27+
status="Please reach us via DM",
28+
in_reply_to_status_id=tweet.id,
29+
)
30+
return new_since_id
31+
32+
def main():
33+
api = create_api()
34+
since_id = 1
35+
while True:
36+
since_id = check_mentions(api, ["help", "support"], since_id)
37+
logger.info("Waiting...")
38+
time.sleep(60)
39+
40+
if __name__ == "__main__":
41+
main()

bots/config.py

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# twitterBot/bots/config.py
2+
import tweepy
3+
import logging
4+
import os
5+
6+
logger = logging.getLogger()
7+
8+
def create_api():
9+
consumer_key = os.getenv("TWITTER_CONSUMER_KEY")
10+
consumer_secret = os.getenv("TWITTER_CONSUMER_SECRET")
11+
access_token = os.getenv("TWITTER_ACCESS_TOKEN")
12+
access_token_secret = os.getenv("TWITTER_ACCESS_TOKEN_SECRET")
13+
14+
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
15+
auth.set_access_token(access_token, access_token_secret)
16+
api = tweepy.API(auth, wait_on_rate_limit=True,
17+
wait_on_rate_limit_notify=True)
18+
try:
19+
api.verify_credentials()
20+
except Exception as e:
21+
logger.error("Error creating API", exc_info=True)
22+
raise e
23+
logger.info("Authentication OK - API created...")
24+
return api

bots/favRetweet.py

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
#!/usr/bin/env python
2+
# twitterBot/bots/favRetweet.py
3+
4+
import tweepy
5+
import logging
6+
from config import create_api
7+
import json
8+
9+
logging.basicConfig(level=logging.INFO)
10+
logger = logging.getLogger()
11+
12+
class FavRetweetListener(tweepy.StreamListener):
13+
def __init__(self, api):
14+
self.api = api
15+
self.me = api.me()
16+
17+
def on_status(self, tweet):
18+
logger.info(f"Processing tweet id {tweet.id}")
19+
if tweet.in_reply_to_status_id is not None or \
20+
tweet.user.id == self.me.id:
21+
# This tweet is a reply or I'm its author so, ignore it
22+
return
23+
if not tweet.favorited:
24+
# Mark it as Liked, since we have not done it yet
25+
try:
26+
tweet.favorite()
27+
except Exception as e:
28+
logger.error("Error on fav", exc_info=True)
29+
if not tweet.retweeted:
30+
# Retweet, since we have not retweeted it yet
31+
try:
32+
tweet.retweet()
33+
except Exception as e:
34+
logger.error("Error on fav and retweet", exc_info=True)
35+
36+
def on_error(self, status):
37+
logger.error(status)
38+
39+
def main(keywords):
40+
api = create_api()
41+
tweets_listener = FavRetweetListener(api)
42+
stream = tweepy.Stream(api.auth, tweets_listener)
43+
stream.filter(track=keywords, languages=["en"])
44+
45+
if __name__ == "__main__":
46+
main(["Python", "Tweepy"])

bots/followfollowers.py

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
#!/usr/bin/env python
2+
# twitterBot/bots/followfollowers.py
3+
4+
import tweepy
5+
import logging
6+
from config import create_api
7+
import time
8+
9+
logging.basicConfig(level=logging.INFO)
10+
logger = logging.getLogger()
11+
12+
def follow_followers(api):
13+
logger.info("Retrieving and following followers")
14+
for follower in tweepy.Cursor(api.followers).items():
15+
if not follower.following:
16+
logger.info(f"Following {follower.name}")
17+
follower.follow()
18+
19+
def main():
20+
api = create_api()
21+
while True:
22+
follow_followers(api)
23+
logger.info("Waiting...")
24+
time.sleep(60)
25+
26+
if __name__ == "__main__":
27+
main()

requirements.txt

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
certifi==2020.6.20
2+
chardet==3.0.4
3+
idna==2.10
4+
oauthlib==3.1.0
5+
PySocks==1.7.1
6+
requests==2.24.0
7+
requests-oauthlib==1.3.0
8+
six==1.15.0
9+
tweepy==3.9.0
10+
urllib3==1.25.9

venv/bin/Activate.ps1

+230
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,230 @@
1+
<#
2+
.Synopsis
3+
Activate a Python virtual environment for the current Powershell session.
4+
5+
.Description
6+
Pushes the python executable for a virtual environment to the front of the
7+
$Env:PATH environment variable and sets the prompt to signify that you are
8+
in a Python virtual environment. Makes use of the command line switches as
9+
well as the `pyvenv.cfg` file values present in the virtual environment.
10+
11+
.Parameter VenvDir
12+
Path to the directory that contains the virtual environment to activate. The
13+
default value for this is the parent of the directory that the Activate.ps1
14+
script is located within.
15+
16+
.Parameter Prompt
17+
The prompt prefix to display when this virtual environment is activated. By
18+
default, this prompt is the name of the virtual environment folder (VenvDir)
19+
surrounded by parentheses and followed by a single space (ie. '(.venv) ').
20+
21+
.Example
22+
Activate.ps1
23+
Activates the Python virtual environment that contains the Activate.ps1 script.
24+
25+
.Example
26+
Activate.ps1 -Verbose
27+
Activates the Python virtual environment that contains the Activate.ps1 script,
28+
and shows extra information about the activation as it executes.
29+
30+
.Example
31+
Activate.ps1 -VenvDir C:\Users\MyUser\Common\.venv
32+
Activates the Python virtual environment located in the specified location.
33+
34+
.Example
35+
Activate.ps1 -Prompt "MyPython"
36+
Activates the Python virtual environment that contains the Activate.ps1 script,
37+
and prefixes the current prompt with the specified string (surrounded in
38+
parentheses) while the virtual environment is active.
39+
40+
41+
#>
42+
Param(
43+
[Parameter(Mandatory = $false)]
44+
[String]
45+
$VenvDir,
46+
[Parameter(Mandatory = $false)]
47+
[String]
48+
$Prompt
49+
)
50+
51+
<# Function declarations --------------------------------------------------- #>
52+
53+
<#
54+
.Synopsis
55+
Remove all shell session elements added by the Activate script, including the
56+
addition of the virtual environment's Python executable from the beginning of
57+
the PATH variable.
58+
59+
.Parameter NonDestructive
60+
If present, do not remove this function from the global namespace for the
61+
session.
62+
63+
#>
64+
function global:deactivate ([switch]$NonDestructive) {
65+
# Revert to original values
66+
67+
# The prior prompt:
68+
if (Test-Path -Path Function:_OLD_VIRTUAL_PROMPT) {
69+
Copy-Item -Path Function:_OLD_VIRTUAL_PROMPT -Destination Function:prompt
70+
Remove-Item -Path Function:_OLD_VIRTUAL_PROMPT
71+
}
72+
73+
# The prior PYTHONHOME:
74+
if (Test-Path -Path Env:_OLD_VIRTUAL_PYTHONHOME) {
75+
Copy-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME -Destination Env:PYTHONHOME
76+
Remove-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME
77+
}
78+
79+
# The prior PATH:
80+
if (Test-Path -Path Env:_OLD_VIRTUAL_PATH) {
81+
Copy-Item -Path Env:_OLD_VIRTUAL_PATH -Destination Env:PATH
82+
Remove-Item -Path Env:_OLD_VIRTUAL_PATH
83+
}
84+
85+
# Just remove the VIRTUAL_ENV altogether:
86+
if (Test-Path -Path Env:VIRTUAL_ENV) {
87+
Remove-Item -Path env:VIRTUAL_ENV
88+
}
89+
90+
# Just remove the _PYTHON_VENV_PROMPT_PREFIX altogether:
91+
if (Get-Variable -Name "_PYTHON_VENV_PROMPT_PREFIX" -ErrorAction SilentlyContinue) {
92+
Remove-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Scope Global -Force
93+
}
94+
95+
# Leave deactivate function in the global namespace if requested:
96+
if (-not $NonDestructive) {
97+
Remove-Item -Path function:deactivate
98+
}
99+
}
100+
101+
<#
102+
.Description
103+
Get-PyVenvConfig parses the values from the pyvenv.cfg file located in the
104+
given folder, and returns them in a map.
105+
106+
For each line in the pyvenv.cfg file, if that line can be parsed into exactly
107+
two strings separated by `=` (with any amount of whitespace surrounding the =)
108+
then it is considered a `key = value` line. The left hand string is the key,
109+
the right hand is the value.
110+
111+
If the value starts with a `'` or a `"` then the first and last character is
112+
stripped from the value before being captured.
113+
114+
.Parameter ConfigDir
115+
Path to the directory that contains the `pyvenv.cfg` file.
116+
#>
117+
function Get-PyVenvConfig(
118+
[String]
119+
$ConfigDir
120+
) {
121+
Write-Verbose "Given ConfigDir=$ConfigDir, obtain values in pyvenv.cfg"
122+
123+
# Ensure the file exists, and issue a warning if it doesn't (but still allow the function to continue).
124+
$pyvenvConfigPath = Join-Path -Resolve -Path $ConfigDir -ChildPath 'pyvenv.cfg' -ErrorAction Continue
125+
126+
# An empty map will be returned if no config file is found.
127+
$pyvenvConfig = @{ }
128+
129+
if ($pyvenvConfigPath) {
130+
131+
Write-Verbose "File exists, parse `key = value` lines"
132+
$pyvenvConfigContent = Get-Content -Path $pyvenvConfigPath
133+
134+
$pyvenvConfigContent | ForEach-Object {
135+
$keyval = $PSItem -split "\s*=\s*", 2
136+
if ($keyval[0] -and $keyval[1]) {
137+
$val = $keyval[1]
138+
139+
# Remove extraneous quotations around a string value.
140+
if ("'""".Contains($val.Substring(0,1))) {
141+
$val = $val.Substring(1, $val.Length - 2)
142+
}
143+
144+
$pyvenvConfig[$keyval[0]] = $val
145+
Write-Verbose "Adding Key: '$($keyval[0])'='$val'"
146+
}
147+
}
148+
}
149+
return $pyvenvConfig
150+
}
151+
152+
153+
<# Begin Activate script --------------------------------------------------- #>
154+
155+
# Determine the containing directory of this script
156+
$VenvExecPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
157+
$VenvExecDir = Get-Item -Path $VenvExecPath
158+
159+
Write-Verbose "Activation script is located in path: '$VenvExecPath'"
160+
Write-Verbose "VenvExecDir Fullname: '$($VenvExecDir.FullName)"
161+
Write-Verbose "VenvExecDir Name: '$($VenvExecDir.Name)"
162+
163+
# Set values required in priority: CmdLine, ConfigFile, Default
164+
# First, get the location of the virtual environment, it might not be
165+
# VenvExecDir if specified on the command line.
166+
if ($VenvDir) {
167+
Write-Verbose "VenvDir given as parameter, using '$VenvDir' to determine values"
168+
} else {
169+
Write-Verbose "VenvDir not given as a parameter, using parent directory name as VenvDir."
170+
$VenvDir = $VenvExecDir.Parent.FullName.TrimEnd("\\/")
171+
Write-Verbose "VenvDir=$VenvDir"
172+
}
173+
174+
# Next, read the `pyvenv.cfg` file to determine any required value such
175+
# as `prompt`.
176+
$pyvenvCfg = Get-PyVenvConfig -ConfigDir $VenvDir
177+
178+
# Next, set the prompt from the command line, or the config file, or
179+
# just use the name of the virtual environment folder.
180+
if ($Prompt) {
181+
Write-Verbose "Prompt specified as argument, using '$Prompt'"
182+
} else {
183+
Write-Verbose "Prompt not specified as argument to script, checking pyvenv.cfg value"
184+
if ($pyvenvCfg -and $pyvenvCfg['prompt']) {
185+
Write-Verbose " Setting based on value in pyvenv.cfg='$($pyvenvCfg['prompt'])'"
186+
$Prompt = $pyvenvCfg['prompt'];
187+
}
188+
else {
189+
Write-Verbose " Setting prompt based on parent's directory's name. (Is the directory name passed to venv module when creating the virutal environment)"
190+
Write-Verbose " Got leaf-name of $VenvDir='$(Split-Path -Path $venvDir -Leaf)'"
191+
$Prompt = Split-Path -Path $venvDir -Leaf
192+
}
193+
}
194+
195+
Write-Verbose "Prompt = '$Prompt'"
196+
Write-Verbose "VenvDir='$VenvDir'"
197+
198+
# Deactivate any currently active virtual environment, but leave the
199+
# deactivate function in place.
200+
deactivate -nondestructive
201+
202+
# Now set the environment variable VIRTUAL_ENV, used by many tools to determine
203+
# that there is an activated venv.
204+
$env:VIRTUAL_ENV = $VenvDir
205+
206+
if (-not $Env:VIRTUAL_ENV_DISABLE_PROMPT) {
207+
208+
Write-Verbose "Setting prompt to '$Prompt'"
209+
210+
# Set the prompt to include the env name
211+
# Make sure _OLD_VIRTUAL_PROMPT is global
212+
function global:_OLD_VIRTUAL_PROMPT { "" }
213+
Copy-Item -Path function:prompt -Destination function:_OLD_VIRTUAL_PROMPT
214+
New-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Description "Python virtual environment prompt prefix" -Scope Global -Option ReadOnly -Visibility Public -Value $Prompt
215+
216+
function global:prompt {
217+
Write-Host -NoNewline -ForegroundColor Green "($_PYTHON_VENV_PROMPT_PREFIX) "
218+
_OLD_VIRTUAL_PROMPT
219+
}
220+
}
221+
222+
# Clear PYTHONHOME
223+
if (Test-Path -Path Env:PYTHONHOME) {
224+
Copy-Item -Path Env:PYTHONHOME -Destination Env:_OLD_VIRTUAL_PYTHONHOME
225+
Remove-Item -Path Env:PYTHONHOME
226+
}
227+
228+
# Add the venv to the PATH
229+
Copy-Item -Path Env:PATH -Destination Env:_OLD_VIRTUAL_PATH
230+
$Env:PATH = "$VenvExecDir$([System.IO.Path]::PathSeparator)$Env:PATH"

0 commit comments

Comments
 (0)