0

How to get a discord username like bot.get_user(id) would in discord.py? I am using hikari, doing a JSON list of all the users in the server, I have their IDs but not the username and I would like it to update periodically.

def retrieveUsernames():
  consoleLog(color.blue,"do get usernames") # log in console
  guild = "xxxx"
  jsonItem = cc.getJson() #get json object
  for key in creamCoin[guild]:


    user = # GET USER OBJECT FROM ID


    name = user.username
    name = bot.rest.get_user(int(key))
    print(key)
    print(name)
    #key acts as user
    jsonItem[guild][key]["username"] = name #update plain text username
  cc.updateJSONDatabase() #commit changes

1 Answer 1

1

Hikari's API calls are asynchronous so you have to either: (1) call them using await in an async function or (2) use asyncio to call them from a non-async function, but it also requires hikari's event loop. All of Hikari's events are async functions, so you can just use await before the API function to call it. If you want to make periodic calls outside of a triggered event, I'd suggest using a separate thread or something like APScheduler to start a Cron-style service.

import hikari
import asyncio
import threading

bot = hikari.GatewayBot(token='...')

@bot.listen(hikari.StartedEvent)
async def on_bot_started(event):
    user = await bot.rest.fetch_user(SOME_USER_ID)
    print(f'Main thread: {user.username}')

    # retrieve usernames in a separate thread
    loop = asyncio.get_running_loop()
    threading.Thread(target=retrieve_usernames, args=[loop, user.id]).start()

def retrieve_usernames(loop: asyncio.AbstractEventLoop, user_id: hikari.Snowflake):
    call_async(asyncio.sleep(1), loop)
    user = call_async(bot.rest.fetch_user(user_id), loop)
    print(f'Separate thread: {user.username}')

def call_async(coro, loop):
    return asyncio.run_coroutine_threadsafe(coro, loop).result()

bot.run()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.