Search code examples
pythonevaltelethon

A better alternative to eval()


I am looking for an alternative to python string evaluator eval()

from telethon import Button

c = "Click Here To Open Google | [Button.url('Google', 'google.com')]"
if "|" in c:
   filter, options= c.split("|")
filter = filter.strip()     
button = options.strip()

g = eval(button)
await event.reply(filter, buttons=g)

the usage of eval() here is dangerous as related to this, what can i use as an alternative ?


Solution

  • A safer alternative is ast.literal_eval but that's very restricted compared to eval(), only works on strings that represent valid Python literals at least for your example.

    Better suggestion to parse string yourself, first you can get the two parameters using regex:

    import re
    
    c = "Click Here To Open Google | [Button.url('Google', 'google.com')]"
    if "|" in c:
       filter, options= c.split("|")
    filter = filter.strip()     
    button = options.strip()
    params = re.findall(r'\'(.*)\'',button)
    

    It returns list of ["Google', 'google.com"] in params.

    Then you can use if to check if it contains malicious input, if then modify it or block user, otherwise unpack to the method using Button.url(*params)