Tasks not running the same as a console

Im developing a discord bot, and this block of code:

user_name = message.content
if message.content.__contains__('u/') == True:
    user_name = user_name.replace('!connect u/', '')
    user_name = user_name.replace('!connect ', '')

user_r = reddit.redditor(user_name)

code = 0
code = code + random.randint(1000,9999)

data = {
  "user name": user_name,
  "code": code,
  "connected": False

with open("users/" + str( + '.json', 'w+') as outfile:
    json.dump(data, outfile, indent=4)
reddit.redditor(user_name).message('Your code for TheRedditBot', 'This is your code: ' + str(code) + '\n\nIf you are being spamed by codes, dm me here:')
await'{} You have been sent a code on reddit. Do `!code [code]` to connect your account, if you have already have a connected account, it was removed')

is not working in a always on task, but works fine in a console

is it to do with the file opening or soming?

what is the error that you are seeing?