簡體   English   中英

為什么“if in”語句不適用於discord.py?

[英]Why isn't the 'if in' statement working with discord.py?

我有我正在處理的 Discord 機器人的以下代碼:

import discord
import random 
from discord.ext import commands, tasks
import os
import time
import asyncio
import re
import urllib.request
import json
from apiclient.discovery import build
from itertools import product, cycle
from discord.ext.tasks import loop

client = commands.Bot(command_prefix =  'v!', description='fff', case_insensitive=True)

token = 'REDEACTED'
client.remove_command("help")

@client.command(pass_context=True)
async def Ban(ctx):

    members = []

    a = (ctx.author)
    print(a)

    m = (ctx.message.content)

    m = m.replace("v!ban ", '')
    print(m)

    with open('members.txt', 'w'): pass

#    print(members)
    for member in ctx.guild.members:

        with open('members.txt', 'a', encoding = "UTF-8") as f:
            f.writelines(str(member) + '\n')

    with open('members.txt', 'r', encoding = "UTF-8") as f:
        members = f.read()

    for i in members:
        if i == m:
            print('True')
        else:
            print("False")

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')
    await client.change_presence(activity = discord.Game("v!help"))

client.run(token)

“members.txt”文件包含:(我的 Discord 服務器的成員)

kurt#6396
galen#2172
xXDEFECTMEXx#0598
xx_kyrah.w#2995
lmao.com#5953
skyanite#1725
Gilly#5865
chef shaq#3889
mariokuhl.RS#0101
UltimateDucc#9121
xSaltyOne#9450
Jacobs Kid#0771
Alex L#7988
✪ csw ✪#0115
smithers#4004
Little5avage#8028
FaZe_Eric#9627
Unib_Rovodkalan#8661

ARX6.#5773
The Bomb#3693

如果我要執行命令v!ban UltimateDucc#9121 ,它會返回False而不是True ,即使該值存在於數組中。

我正在努力實現的目標:

收集服務器成員 -完成

放入文件 -完成

從用戶獲取輸入 -完成

檢查輸入是否在文件中 -卡住

任何幫助表示贊賞。

f.read()將返回一個包含文件內容的字符串。
當您遍歷它時, i將成為該字符串中的每個字符。

您應該使用list(f)f.readlines()並在末尾f.readlines()換行符

有關更多信息,請參閱https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects

添加了注釋以進行澄清,但您的基本問題是您正在從文件中迭代加載列表中的所有字符,並檢查它們中的每一個是否等於用戶提供的字符串。

@client.command(pass_context=True)
async def Ban(ctx):

    members = []

    a = (ctx.author)
    print(a)

    m = (ctx.message.content)

    m = m.replace("v!ban ", '')
    print(m)

    with open('members.txt', 'w'): pass

    # I swapped the order here because otherwise the file gets opened each iteration
    with open('members.txt', 'a', encoding = "UTF-8") as f:
        for member in ctx.guild.members:
            f.write(str(member) + '\n') # you don't have to use writelines here because you are only writing a single line

    with open('members.txt', 'r', encoding = "UTF-8") as f:
        members = f.read().split('\n') # we want a list of members, not a string containing all of them

    # we can just use the "in" operator here, it checks if our string is in the loaded list
    if m in members:
        print('True')
    else:
        print("False")

不要使用這個:

# code block 1
for i in members:
    if i == m:
        print('True')
    else:
        print("False")

用這個:

# code block 2
if i in members:
    print('true')
else:
    print('false')

或者

用這個:

# code block 3 
x = members.split('\n')
if i in members:
    print('true')
else:
    print('false')

在代碼塊 1 中:逐個字符地進行比較。 您正在將文件中的每個字符與用戶輸入的字符串進行比較。

在代碼塊 2 中:Python 在給定字符串中查找子字符串 。 即:如果用戶輸入的字符串存在於文件內容中,它將返回 True。

在代碼塊 3 中:將文件內容逐行拆分,並將每個條目存儲在一個數組中。 然后查看用戶輸入的字符串是否在這個數組中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM