Search code examples
pythonpython-2.7botsirctwitch

Python - Add multiple values to text file from same variable


I am developing a Twitch IRC Bot using Python, and recently I implemented song requests. Strangely enough, the main problem I'm stuck on is storing the songs in a separate text file, list, or set. Currently, this is how I retrieve the songs for the list:

  1. User types in !songrequest [URL].
  2. Bot processes URL and extracts a song title from it.
  3. Bot sends a confirmation message, and stores the song name in a variable.

So, because of the song titles all being stored in the same variable, it constantly overrides itself, even if put in a set. I am new to Python, so if anyone could help me out and tell me how I would be able to send each unique song title to a set, list, etc., I would be very glad! Thanks in advance!

My code:

if message.startswith("!songrequest"):
        request = message.split(' ')[1]
        youtube = etree.HTML(urllib.urlopen(request).read())
        video_title = youtube.xpath("//span[@id='eow-title']/@title")
        song = ''.join(video_title)
        requests = set()
        requests.add(song + "\r\n")
        sendMessage(s, song + " has been added to the queue.")
        with open("requests.txt", "w") as text_file:
            text_file.write(str(requests))
        break

If you find any other suggestions for cleaning up my coding, please tell me them down below!


Solution

  • Let's clean this up by creating a function:

    if message.startswith("!songrequest"):
        song = message.split(' ', 1)[1]   # Add max=1 to split()
        message = request_song(song)
        sendMessage(s, message)
        break
    

    Now let's write the request_song(title) function. I think you should keep a unique list of requested songs, and tell the user if a song has already been requested. When you play a song, you can clear the request (presumably when you play it, everybody that requested it will hear it and be satisfied). The function can return an appropriate message, determined by what action it takes.

    def request_song(song:str) -> str:
        """
        Add a song to the request queue. Return a message to be sent
        in response to the request. If the song is new to the list, reply
        that the song has been added. If the song is already on the list,
        or banned, reply to that effect.
        """
        if song.startswith('http'):
            if 'youtube' not in song:
                return "Sorry, only youtube URLs are supported!"
    
            youtube = etree.HTML(urllib.urlopen(request).read())
            song_title = youtube.xpath("//span[@id='eow-title']/@title")
        else:
            song_title = song.strip().lower()
    
        with open('requests.txt') as requestfile:
            requests = set(line.strip().lower() for line in requestfile)
    
        if song_title in requests:
            return "That song is already in the queue. Be patient!"
    
        # Just append the song to the end of the file
        with open('requests.txt', 'a') as f:
            print(file=f, song_title)
    
        return "'{}' has been added to the queue!".format(song_title)