Search code examples
pythonloopsdiscordcycle

Why it inly loops 4 times?


Why my commands only loops 4 times but I have put x as 100 times not 4. Can someone help me with this! I don't understand this bug and I need to fix this till friday

import discord
from discord.ext import commands, tasks
import asyncio
import keyboard
import time
from pynput.mouse import Button, Controller
from pynput.keyboard import Key, Controller
from pynput.keyboard import Controller
from pynput import mouse
import mouse

TOKEN = 'mytoken...'

client = commands.Bot(command_prefix = '.')

@client.command(name='play')
async def play(ctx):

    await ctx.channel.send("Hello! welcome to a game where you play my game through discord messages! How yo play: if you want to go write - 'go', left - 'left', right - 'right', back - 'back', sprint 'lgo', click - 'click', jump - 'jump'")

    
    
    x = '100'
    for x in 'play':


        
        msg = await client.wait_for('message')
        response = (msg.content)
        print(response)
    
    
        if response == "go":

            
            keyboard.press('w')
            time.sleep(2)
            keyboard.release('w')
    
        if  response == "left":   
            
            keyboard.press('a')
            time.sleep(2)
            keyboard.release('a')
        
        if response == "right":

            
            keyboard.press('d')
            time.sleep(2)
            keyboard.release('d')
    
        if  response == "back":   
            
            keyboard.press('s')
            time.sleep(2)
            keyboard.release('s')
        
        if response == "jump":

            
            keyboard.press('b')
            keyboard.release('b')
    
        if  response == "click":   
            
            mouse.click('left')
        
        if response == "lgo":

            
            keyboard.press('shift + w')
            time.sleep(5)
            keyboard.release('w')

            

client.run(TOKEN)

I'm making a discord bot that can play my game through discord messages, but I have this weird bug ware it loops 4 times instead of 100 times as it's put to do


Solution

  • It only loops 4 times because you are iterating over the string play.

    x = '100' 
    for x in 'play':
      print(x)
    

    this outputs:

    p
    l
    a
    y
    

    (and completely ignores the 100, as it gets overwritten in the loop)

    To loop 100 times use:

    x = 100 # number, not string
    for i in range(x):
      print(i)
    

    this outputs:

    0
    1
    2
    3
    ...
    98
    99
    

    and x keeps the value 100