Skip to content

Poll Voter

Published: 2020-11-15

Poll Voter is a "Bot" that automatically votes for a certain, user specified option on an online poll artificially changing the results.

The original code is below with the refactored version in OOP.

Poll Vote Code

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
#!/usr/bin/env python3

# Load libraries
import logging
import random
import datetime
import os
import sys
import time
import json
import requests

from torpy import TorClient
from torpy.http.adapter import TorHttpAdapter
from bs4 import BeautifulSoup as BeaSoup

# Constants
RETRIES = 3
OWNP = os.path.abspath(os.path.dirname(sys.argv[0]))
LOGFILE = '/media/sf_data/scriptsout/vote/vote.txt'

# Setup Logging
logging.basicConfig(
    format='%(asctime)s:%(levelname)s:%(message)s',
    level=logging.INFO,
    filename=LOGFILE)

# Storage for the useragent strings from file
#   facilitates picking at random
useragents = []

# Make it look like a real browser
headers = {
    "Accept": "text/html,application/xhtml+xml,application/xml; \
        q=0.9,image/webp,*/*;q=0.8",
    "Accept-Encoding": "gzip, deflate, br",
    "Accept-Language": "en-US,en;q=0.5",
    "DNT": "1",
    "Host": "", # set at runtime
    "Upgrade-Insecure-Requests": "1",
    "User-Agent": "", # set at runtime
    "Cache-Control": "max-age=0",
    "Connection": "keep-alive"
}

poll_id = "10614272" # change for a different poll
poll_winner = "49167224" # which item to vote for | 49167240, 49167239, 49167224

# Poll base url
url_poll = (
    "https://poll.fm/"
    + poll_id
)

# Generated URL to be submited for vote
url_template = (
    "https://poll.fm/vote?"
    "va={item_va}"
    "&pt=0"
    "&r={item_r}"
    "&p=" + poll_id +
    "&a=" + poll_winner + ","
    "&o="  # nothing needed here
    "&t={item_t}"
    "&token={item_token}"
    "&pz={item_pz}"
)

# *****************************************************************************
# Helper Functions
# *****************************************************************************

# Loads the user agents from file into the array
def get_useragents():
    logging.info("Loading useragent strings")
    with open(OWNP + '/useragent.txt', 'r') as f:
        for line in f:
            useragents.append(line.rstrip('\n').rstrip('\r'))    

# *****************************************************************************
# Main Function
# *****************************************************************************

def main():
    getdata = True

    try:
        get_useragents() # Load user agents
        headers["Host"] = "poll.fm"

        while getdata: # Loop until there is a problem
            tor = TorClient() # Let's use Tor, shall we....

            with tor.get_guard() as guard:
                adapter = TorHttpAdapter(guard, 3, retries=RETRIES)

                with requests.Session() as s:
                    s.mount('http://', adapter)
                    s.mount('https://', adapter)

                    # Make it look like a different browser randomly
                    #   by changing the user-agent with every request
                    line_no = random.randint(0, len(useragents)-1)
                    cur_useragent = useragents[line_no]
                    headers["User-Agent"] = cur_useragent
                    logging.info("User-Agent set to: %s" % cur_useragent)

                    # Go to poll main page to get the needed items
                    #   to submit for the vote
                    logging.info("Getting: %s" % url_poll)
                    r = s.get(url_poll, headers=headers)
                    logging.info(
                            "First response: %s" 
                            % r.status_code 
                            + " " 
                            + r.url
                        )
                    r.raise_for_status()

                    # Get the html from the web page
                    bs_content = BeaSoup(r.content, "lxml")

                    # Get the info from the Vote button json object
                    button_data = bs_content.find('a', 
                        class_="vote-button css-vote-button pds-vote-button")

                    v_bdata = button_data.attrs.get('data-vote')

                    # Load as json data
                    bdata = json.loads(v_bdata)

                    # Get hidden form value
                    v_pz = bs_content.find(attrs={"name": "pz"})

                    # Inject data into vote URL template
                    url_vote = url_template  # reset url_vote
                    url_vote = url_vote.replace("{item_t}", str(bdata['t']))
                    url_vote = url_vote.replace("{item_token}", str(bdata['n']))
                    url_vote = url_vote.replace("{item_pz}", str(v_pz['value']))
                    url_vote = url_vote.replace("{item_r}", str(bdata['b']))
                    url_vote = url_vote.replace("{item_va}", str(bdata['at']))

                    # Makes it look slightly more authentic, by waiting 
                    #  before actually submitting the vote after the
                    #  initial request to the poll.
                    logging.info("Waiting 2 seconds before submitting.")
                    time.sleep(2)

                    # Let's vote!
                    logging.info("Getting: %s" % url_vote)
                    r = s.get(url_vote, headers=headers)

                    # Redirected response, log it
                    if r.history:
                        logging.info("Request redirected")
                        for resp in r.history:
                            logging.info(
                                "Redirected response: %s" 
                                % resp.status_code 
                                + " " 
                                + resp.url
                            )

                    logging.info(
                            "Final destination: %s" 
                            % r.status_code 
                            + " " 
                            + r.url
                        )

                    r.raise_for_status()

                    # Wait a random number of seconds between 5 & 20
                    #  before starting again - more realistic
                    wait_time = random.randint(5, 20)
                    logging.info("Waiting %i seconds." % (wait_time))
                    time.sleep(wait_time)

    # Any issues, log them and get out.
    except Exception as e:
        logging.error(e)

        # Exit loop
        getdata = False

# *****************************************************************************
# Script Starting Point
# *****************************************************************************
if __name__ == "__main__":
    main()

Poll Vote Code (OOP)

Main (vote.py)

  • Main entry point/start of program
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#!/usr/bin/env python3

# Load libraries
import logging

from voting import PollFMVoter

LOGFILE = '/media/sf_data/scriptsout/vote/vote.txt'

# Setup Logging
logging.basicConfig(
    format='%(asctime)s:%(levelname)s:%(message)s',
    level=logging.INFO,
    filename=LOGFILE)

# *****************************************************************************
# Main Function
# *****************************************************************************

def main():
    myvtr = PollFMVoter()
    myvtr.poll_id = "10614272"
    myvtr.poll_option = "49167239"
    myvtr.getVotes()

# *****************************************************************************
# Script Starting Point
# *****************************************************************************
if __name__ == "__main__":
    main()

AutoVoter (voter.py)

  • "Generic" Class to inherit from with common code.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# Load libraries
import logging
import random
import os
import sys

from abc import abstractmethod, abstractproperty

# Constants
OWNP = os.path.abspath(os.path.dirname(sys.argv[0]))

logger = logging.getLogger(__name__)

class AutoVoter:
    def __init__(self):
        self._useragents = []

        self._url_poll = ""
        self._url_template = ""

        # Make it look like a real browser
        self._headers = {
            "Accept": "text/html,application/xhtml+xml,application/xml; \
                q=0.9,image/webp,*/*;q=0.8",
            "Accept-Encoding": "gzip, deflate, br",
            "Accept-Language": "en-US,en;q=0.5",
            "DNT": "1",
            "Host": "", # set at runtime
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "", # set at runtime
            "Cache-Control": "max-age=0",
            "Connection": "keep-alive"
        }

        self.__get_useragents()

    # Loads a new, random user-agent string   
    def _set_useragent(self):
        line_no = random.randint(0, len(self._useragents)-1)
        logger.info("User-agent set as: %s" % self._useragents[line_no]) 
        self._headers["User-Agent"] = self._useragents[line_no]

    # Loads the user agents from file into the array
    def __get_useragents(self):
        logger.info("Loading useragent strings")
        with open(OWNP + '/voting/useragent.txt', 'r') as f:
            for line in f:
                self._useragents.append(line.rstrip('\n').rstrip('\r')) 

    @abstractmethod
    def __getVote(self):
        pass

    @abstractmethod
    def getVotes(self):
        pass

PollFMVoter (pollfm.py)

  • More specific class, inherits from AutoVoter and implements specifics.
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# Load libraries
import logging
import random
import time
import json
import requests

from torpy import TorClient
from torpy.http.adapter import TorHttpAdapter
from bs4 import BeautifulSoup as BeaSoup

from voting.voter import AutoVoter

logger = logging.getLogger(__name__)

class PollFMVoter(AutoVoter):
    def __init__(self):
        super().__init__()
        self._headers["Host"] = "poll.fm"

        self.poll_id = ""
        self.poll_option = ""
        self.poll_votes = 0

        self.__vote_pointer = 0
        self.__retries = 3
        self.__url_poll = "https://poll.fm/{poll_id}"

        # Generated URL to be submited for vote
        self.__url_template = (
            "https://poll.fm/vote?"
            "va={item_va}"
            "&pt=0"
            "&r={item_r}"
            "&p={item_pid}"
            "&a={item_opt},"
            "&o="  # nothing needed here
            "&t={item_t}"
            "&token={item_token}"
            "&pz={item_pz}"
        )

    def __getVote(self):
        try:
            self.__vote_pointer += 1
            tor = TorClient()

            with tor.get_guard() as guard:
                adapter = TorHttpAdapter(guard, 3, retries=self.__retries)

                with requests.Session() as s:
                    s.mount('http://', adapter)
                    s.mount('https://', adapter)

                    # Make it look like a different browser randomly
                    #   by changing the user-agent with every request
                    self._set_useragent()

                    # Set the poll id in the url
                    self.__url_poll = self.__url_poll.replace("{poll_id}", self.poll_id)

                    # Go to poll main page to get the needed items
                    #   to submit for the vote
                    logger.info("Getting: %s" % self.__url_poll)
                    r = s.get(self.__url_poll, headers=self._headers)
                    logger.info(
                            "First response: %s" 
                            % r.status_code 
                            + " " 
                            + r.url
                        )
                    r.raise_for_status()

                    # Get the html from the web page
                    bs_content = BeaSoup(r.content, "lxml")

                    # Get the info from the Vote button json object
                    button_data = bs_content.find('a', 
                        class_="vote-button css-vote-button pds-vote-button")

                    v_bdata = button_data.attrs.get('data-vote')

                    # Load as json data
                    bdata = json.loads(v_bdata)

                    # Get hidden form value
                    v_pz = bs_content.find(attrs={"name": "pz"})

                    # Inject data into vote URL template
                    url_vote = self.__url_template  # reset url_vote

                    url_vote = url_vote.replace("{item_pid}", self.poll_id)
                    url_vote = url_vote.replace("{item_opt}", self.poll_option)
                    url_vote = url_vote.replace("{item_t}", str(bdata['t']))
                    url_vote = url_vote.replace("{item_token}", str(bdata['n']))
                    url_vote = url_vote.replace("{item_pz}", str(v_pz['value']))
                    url_vote = url_vote.replace("{item_r}", str(bdata['b']))
                    url_vote = url_vote.replace("{item_va}", str(bdata['at']))

                    # Makes it look slightly more authentic, by waiting 
                    #  before actually submitting the vote after the
                    #  initial request to the poll.
                    logger.info("Waiting 2 seconds before submitting.")
                    time.sleep(2)

                    # Let's vote!
                    logger.info("Submitting vote %i: %s" 
                                    % (self.__vote_pointer, url_vote))
                    r = s.get(url_vote, headers=self._headers)

                    # Redirected response, log it
                    if r.history:
                        logger.info("Request redirected")
                        for resp in r.history:
                            logger.info(
                                "Redirected response: %s" 
                                % resp.status_code 
                                + " " 
                                + resp.url
                            )

                    logger.info(
                            "Final destination: %s" 
                            % r.status_code 
                            + " " 
                            + r.url
                        )

                    r.raise_for_status()

                    if (self.__vote_pointer != self.poll_votes): 
                        # Wait a random number of seconds between 5 & 20
                        #  before starting again - more realistic
                        wait_time = random.randint(5, 20)
                        logger.info("Waiting %i seconds." % (wait_time))
                        time.sleep(wait_time)

        # Any issues, log them and get out
        except Exception as e:
            logger.error(e)
            raise


    def getVotes(self):
        getdata = True
        self.__vote_pointer = 0

        # No sense in doing anything without a poll id 
        #   and an option to vote for
        if (self.poll_option != "" and self.poll_id != ""):
            try:
                # If set to 0, run continuously
                if (self.poll_votes == 0):
                    while getdata:
                        self.__getVote()
                else: 
                    for _ in range(self.poll_votes):
                        self.__getVote()

            except Exception as e:
                logger.error(e)
                getdata = False
        else:
            logger.info("Please set Poll ID & Option.")