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

#!/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
#!/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.
# 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.
# 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.")