Search code examples
pythonjsondiscorddiscord.py

how to append into a json file from a dictionary [Discord.py]


I want to append a total number of message send by a user in a channel into a json file , it should look something like this

'name' : 'xx',
'channel' : 123456789,
'total_no_of_messages' : 1234

I'm currently using this code to get channel and user details and adding it into a dictionary , but I don't know how to dump it into a json file

@client.event
async def on_ready():
    channels = []
    users = []
    data = {}
    for i in dct_channels.values():
      for j in i:
        channels.append(j)
      
    for j in dct_memb.values():
      for i in j:
        users.append(i)
  
    messages = []
    for j in channels:
      channel = client.get_channel(j)
      if isinstance(channel, discord.TextChannel):
        async for message in channel.history(limit=None):         
          for i in users:
            user = client.get_user(i)
            if message.author == user:  
              messages.append(message.content) 
              data.setdefault(f'{user , channel}', [])     
              data[f'{user,channel}'].append(len(messages))
              print(data)

Solution

  • I ended up using csv to do this

    data = pd.DataFrame(columns=['channel','author'])
        text_channel_list = []
        for i in guild:
          g = client.get_guild(i)
          for channel in g.channels:
            if str(channel.type) == 'text':
              text_channel_list.append(channel)
        
        for j in text_channel_list:
          channel = client.get_channel(j.id)
          
          async for msg in channel.history(limit=100000):
            if msg.author != client.user:                                                              
                    data = data.append({'channel':msg.channel.name,
                                        'author': msg.author}, ignore_index=True)
            if len(data) == 100000:
                break
            
          file_location = "data.csv"
          data.to_csv(file_location)