2016-02-19 53 views
0

我正在開發一個使用Python的Twitch IRC Bot,最近我實現了歌曲請求。奇怪的是,我堅持的主要問題是將歌曲存儲在單獨的文本文件,列表或設置中。目前,這是我如何檢索歌曲的列表:Python - 將多個值添加到來自同一變量的文本文件

  1. 用戶類型in!songrequest [URL]。
  2. Bot處理URL並從中提取歌曲標題。
  3. Bot發送確認信息,並將歌曲名稱存儲在變量中。

因此,由於歌曲標題全部存儲在同一個變量中,即使置於一個集合中,它也會不斷地覆蓋自身。我是Python新手,所以如果任何人都可以幫助我,告訴我怎樣才能將每首獨特的歌曲標題發送到一個集合,列表等,我會很高興!提前致謝!

我的代碼:

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 

如果發現清理我的編碼任何其他建議,請告訴我,他們樓下!

+0

您對文本文件有什麼期待? – tzaman

+0

@tzaman我還沒有想過,主要是爲了讓我能夠通讀和播放列出的歌曲,但是我可能會嘗試找到一種方法將文件中的字符串自動播放。 – PixelBeaver

+0

那麼,爲什麼一個文件,而不是隻保留內存字典/設置/等? – tzaman

回答

0

讓我們清理它通過創建一個函數:

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

現在讓我們寫request_song(標題)功能。我想你應該保留一個唯一的請求歌曲列表,並告訴用戶是否已經請求了一首歌曲。當您播放歌曲時,您可以清除請求(大概在您播放歌曲時,每個請求它的人都會聽到並得到滿足)。該函數可以返回一個適當的消息,由其採取的操作決定。

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) 
+0

謝謝,但是當我運行程序時,它在'def request_song(song:str) - > str:'行指向冒號時給了我一個無效的語法錯誤。我嘗試瞭解我所知道的一切(這不是很多:P)來解決它,但是我無法解決這個錯誤。有任何想法嗎? – PixelBeaver

+0

如果您使用的是較舊版本的python,只需要刪除它:'request_song(song):' –

+0

哦,好的,謝謝! – PixelBeaver

相關問題